method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
|---|---|---|
1c4a3a28-a0a6-4735-8f57-a88552fe8c24
| 2
|
public Tile getOtherTile(Tile currentTile){
if (currentTile == null){
throw new IllegalArgumentException("currentTile may not be null");
}
if (currentTile == tile1) return tile2;
return tile1;
}
|
613f7c06-5f7f-44df-b0cc-e18c1ea2f97c
| 2
|
public int getModifiers() {
ClassFile cf = getClassFile2();
int acc = cf.getAccessFlags();
acc = AccessFlag.clear(acc, AccessFlag.SUPER);
int inner = cf.getInnerAccessFlags();
if (inner != -1 && (inner & AccessFlag.STATIC) != 0)
acc |= AccessFlag.STATIC;
return AccessFlag.toModifier(acc);
}
|
56dada18-430d-48ff-83a8-c2dc84732e54
| 7
|
public static int svm_check_probability_model(svm_model model)
{
if (((model.param.svm_type == svm_parameter.C_SVC || model.param.svm_type == svm_parameter.NU_SVC) &&
model.probA!=null && model.probB!=null) ||
((model.param.svm_type == svm_parameter.EPSILON_SVR || model.param.svm_type == svm_parameter.NU_SVR) &&
model.probA!=null))
return 1;
else
return 0;
}
|
ab6244c9-0cce-4f36-a135-feedfaa3dc06
| 1
|
public double evaluate(double x) {
if(x < 0) return 0;
return 1;
}
|
1bbeab1b-eff7-4299-8871-e28feb7c13f0
| 2
|
public static final int StateUpdateChar(int index)
{
if (index < 4)
return 0;
if (index < 10)
return index - 3;
return index - 6;
}
|
7cca406b-f5fd-41fe-88ce-40a2e3d907c0
| 7
|
@Override
public void moveSessionToCorrectThreadGroup(final Session session, int theme)
{
final int themeDex=CMath.firstBitSetIndex(theme);
if((themeDex>=0)&&(themeDex<Area.THEME_BIT_NAMES.length))
{
final ThreadGroup privateGroup=CMProps.getPrivateOwner(Area.THEME_BIT_NAMES[themeDex]+"PLAYERS");
if((privateGroup!=null)
&&(privateGroup.getName().length()>0)
&&(!privateGroup.getName().equals(session.getGroupName())))
{
if(session.getGroupName().length()>0)
{
if(CMLib.library(session.getGroupName().charAt(0), CMLib.Library.SESSIONS)
!= CMLib.library(privateGroup.getName().charAt(0), CMLib.Library.SESSIONS))
{
((Sessions)CMLib.library(session.getGroupName().charAt(0), CMLib.Library.SESSIONS)).remove(session);
((Sessions)CMLib.library(privateGroup.getName().charAt(0), CMLib.Library.SESSIONS)).add(session);
}
}
session.setGroupName(privateGroup.getName());
}
}
}
|
8d6f733b-52b3-4814-80ef-7b86cdaa38d5
| 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(GUI_ModificarPorcentaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GUI_ModificarPorcentaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GUI_ModificarPorcentaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GUI_ModificarPorcentaje.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_ModificarPorcentaje().setVisible(true);
}
});
}
|
736d16ea-09e5-4de9-81f5-2d18e1650a9e
| 7
|
public int firstMissingPositive(int[] A) {
int len = A.length;
for (int i =0;i<len;i++){
while (A[i]!=i+1&&A[i]<=len&&A[i]>0&&A[i]!=A[A[i]-1]){
int temp = A[A[i]-1];
A[A[i]-1] = A[i];
A[i] = temp;
}
}
for (int i =0;i<len;i++) {
if(A[i]!=i+1){
return i+1;
}
}
return len+1;
}
|
54d2fa45-0b67-40f5-acbe-f42c2c0b1788
| 9
|
public void renderizarEntidad(int xp, int yp, RepresentacionEntidad rep)
{
Sprite sprite = rep.getSprite();
final int tamanio = sprite.getTamanio();
xp -= xOffset;
yp -= yOffset;
for(int y = 0; y < tamanio; y++)
{
int ya = y + yp;
if(ya < 0 || ya >= altura)
break;
for(int x = 0; x < tamanio; x++)
{
int xa = x + xp;
if(xa < 0 || xa >= anchura)
break;
//Solo si el sprite está visible en pantalla [validado con los
//2 if anteriores, se pondrá su pixel en la pantalla
//en caso contrario no se pondrá nada, ahorrando
//tiempo de procesamiento.
int color = sprite.pixeles[x + y * tamanio];
if(rep instanceof Perseguidor && color == 0xFFED1C24)
color = 0xFF0000FF;
if(color != 0xFFFF00FF)
pixeles[xa + ya * anchura] = color;
}
}
}
|
cdb202ff-9404-4181-8131-e38ed6815a35
| 6
|
public OptionsMenu() {
super();
/*try {
displayModes = Display.getAvailableDisplayModes();
for(DisplayMode d : displayModes)
modes += d.toString() + "\n";
} catch (LWJGLException e) {
e.printStackTrace();
}*/
Label optionsLabel = new Label("Options");
optionsLabel.setPosition(() -> Camera.get().getDisplayWidth(0.5f), () -> Camera.get().getDisplayHeight(0.1f));
optionsLabel.setHorizontalAlign(HorizontalAlign.CENTER);
add(optionsLabel);
Slider musicSlider = new Slider(SoundStore.get().getMusicVolume());
musicSlider.setPosition(() -> Camera.get().getDisplayWidth(0.35f), () -> Camera.get().getDisplayHeight(0.1667f));
musicSlider.setVerticalAlign(VerticalAlign.CENTER);
musicSlider.addValueChangeListener(e -> {
if(SoundStore.get().getMusicVolume() != musicSlider.getValue()) {
SoundStore.get().setMusicVolume((float) musicSlider.getValue());
SoundStore.get().setCurrentMusicVolume((float) musicSlider.getValue());
}
});
add(musicSlider);
Label musicLabel = new Label("Music Volume ");
musicLabel.setPosition(() -> Camera.get().getDisplayWidth(0.35f), () -> Camera.get().getDisplayHeight(0.1667f));
musicLabel.setAlignments(VerticalAlign.CENTER, HorizontalAlign.RIGHT);
add(musicLabel);
Slider sfxSlider = new Slider(SoundStore.get().getSoundVolume());
sfxSlider.setPosition(() -> Camera.get().getDisplayWidth(0.35f), () -> Camera.get().getDisplayHeight(0.215f));
sfxSlider.setVerticalAlign(VerticalAlign.CENTER);
sfxSlider.addValueChangeListener(e -> {
if(SoundStore.get().getSoundVolume() != sfxSlider.getValue()) {
SoundStore.get().setSoundVolume((float) sfxSlider.getValue());
}
});
add(sfxSlider);
Label sfxLabel = new Label("Sound Volume ");
sfxLabel.setPosition(() -> Camera.get().getDisplayWidth(0.35f), () -> Camera.get().getDisplayHeight(0.215f));
sfxLabel.setAlignments(VerticalAlign.CENTER, HorizontalAlign.RIGHT);
add(sfxLabel);
CheckBox fullscreenCheck = new CheckBox("Fullscreen");
fullscreenCheck.setPosition(() -> Camera.get().getDisplayWidth(0.6f), () -> Camera.get().getDisplayHeight(0.15f));
fullscreenCheck.setChecked(Camera.get().isFullscreen());
fullscreenCheck.addActionListener(e -> Camera.get().setFullscreen(fullscreenCheck.isChecked()));
add(fullscreenCheck);
CheckBox vsyncCheck = new CheckBox("VSync");
vsyncCheck.setPosition(() -> Camera.get().getDisplayWidth(0.6f), () -> fullscreenCheck.getBounds().getMaxY());
vsyncCheck.setChecked(Camera.get().isVSyncEnabled());
vsyncCheck.addActionListener(e -> Camera.get().setVSync(vsyncCheck.isChecked()));
add(vsyncCheck);
Keybind keyValue;
ElementGroup<UIElement> keyGroup;
LinkedList<ElementGroup<UIElement>> keybinds = new LinkedList<ElementGroup<UIElement>>();
for(int keyX = 0; keyX < 2; keyX++) {
final int xOffset = keyX;
for(int keyY = 0; keyY < 12; keyY++) {
final int yOffset = keyY;
try {
keyValue = Keybind.values()[(keyX * 12) + keyY];
} catch(IndexOutOfBoundsException e) {
break;
}
keyGroup = new ElementGroup<UIElement>();
Label keyLabel = new Label(keyValue.toString() + ": ");
keyLabel.setPosition(() -> Camera.get().getDisplayWidth(0.333f) + (xOffset * Camera.get().getDisplayWidth(0.333f)),
() -> Camera.get().getDisplayHeight(0.275f) + (yOffset * keyLabel.getBounds().getHeight()));
keyLabel.setHorizontalAlign(HorizontalAlign.RIGHT);
keyGroup.add(keyLabel);
InputBox keyInput = new InputBox(keyValue.getKey(), InputStyle.KEYBINDS, 0);
keyInput.setPosition(() -> Camera.get().getDisplayWidth(0.333f) + (xOffset * Camera.get().getDisplayWidth(0.333f)),
() -> Camera.get().getDisplayHeight(0.275f) + (yOffset * keyLabel.getBounds().getHeight()));
keyInput.setState(DISABLED);
keyInput.addActionListener(e -> OptionsMenu.this.setFocus(keyInput));
keyInput.addValueChangeListener(e -> {
Keybind.valueOf(keyLabel.getText().split(":")[0]).setKey(Keyboard.getKeyIndex(keyInput.getText()));
keyInput.setState(DISABLED);
});
keyGroup.add(keyInput);
keybinds.add(keyGroup);
add(keybinds.getLast());
}
}
Button close = new Button("Close");
close.setPosition(() -> Camera.get().getDisplayWidth(0.5f), () -> Camera.get().getDisplayHeight(0.85f));
close.setHorizontalAlign(HorizontalAlign.CENTER);
close.addActionListener(e -> setState(KILL_FLAG));
add(close);
addKeybindListener(e -> {
if(e.getKeybind().equals(Keybind.CANCEL)) {
setState(KILL_FLAG);
}
});
setFrame("Menu2");
setBounds(() -> Camera.get().getDisplayWidth(0.2f), () -> Camera.get().getDisplayHeight(0.1f),
() -> Camera.get().getDisplayWidth(0.6f), () -> Camera.get().getDisplayHeight(0.8f));
}
|
deb08bce-cf3c-4d64-9e2e-5f4d9d812778
| 5
|
private boolean isValidCard(Card playedCard) {
// Grab our player index who wishes to play this card.
int curPlayerIndex = (this.firstToPlayIndex + this.cardsPlayed.getNumCards()) % PLAYER_COUNT;
Pile curPlayerHand = this.players[curPlayerIndex].getHandPile();
// If our card isn't even in our hand, there's a real problem
if (!curPlayerHand.containsCard(playedCard)) {
// Report critical error (player chose a card they didn't even have to play for their trick...)
this.roundStats.logError("Player " + (curPlayerIndex + 1) + " chose to play a card they didn't have in their hand", true, this.indentationLevel);
}
// If leading suit hasn't been played, we can play anything.
if(this.cardsPlayed.getNumCards() == 0)
return true;
// Leading suit has been played.. Get the suit
Card.CARD_SUIT leadingSuit = this.cardsPlayed.getCard(0).getSuit();
// Check if the user's hand has a card of this suit.
boolean hasSuit = false;
for(int i = 0; i < curPlayerHand.getNumCards(); i++)
if(curPlayerHand.getCard(i).getSuit() == leadingSuit) {
hasSuit = true;
break;
}
// If we don't have the suit, play anything.
if(!hasSuit)
return true;
// We do have the suit, so lets make sure they played a card of it..
return playedCard.getSuit() == leadingSuit;
}
|
2856b37b-c559-4279-9a21-71a698695592
| 8
|
public static boolean areIdenticalIterative(ListNode l1, ListNode l2) {
ListNode ptr1 = l1;
ListNode ptr2 = l2;
while (true) {
if (ptr1 == null && ptr2 == null) {
return true;
}
if (ptr1 == null && ptr2 != null) {
return false;
}
if (ptr2 == null && ptr1 != null) {
return false;
}
if (ptr1.data != ptr2.data) {
return false;
}
ptr1 = ptr1.next;
ptr2 = ptr2.next;
}
}
|
74f622a1-7eca-4503-9869-5d24d62135e1
| 6
|
public Object getMedianElement() {
if (listHolder == null) {
System.out.println("Provided list is null.");
return null;
}
if (listHolder.next() == null
&& listHolder.getElement() == null) {
System.out.println("Provided list is empty.");
return null;
}
if (listHolder.next() == null) {
return listHolder.getElement();
}
Node median = listHolder;
Node iterator = listHolder.next();
boolean odd = true;
while (iterator.next() != null) {
if (odd) {
iterator = iterator.next();
} else {
iterator = iterator.next();
median = median.next();
}
odd = !odd;
}
return median.getElement();
}
|
32ef2081-b50b-44ee-b5f0-c72165bb8851
| 8
|
Component getComponent(String GComponentInterfaceClassName) {
String clazz = GComponentInterfaceClassName;
if (!(clazz == null) && !(clazz.equals(""))) {
Class t = clazz2Class(clazz);
Constructor c = null;
Object[] o = {blackboard};
try {
c = t.getConstructor(BlackBoard.class);
} catch (NoSuchMethodException e) {
try {
c = t.getConstructor(new Class[]{});
o = new Object[]{};
} catch (NoSuchMethodException e1) {
System.err.println("the clazz " + clazz + "does not have a constructor(blackboard) or constructor(), how can i load it?");
e1.printStackTrace();
}
// ExceptionHandler.catchException(e);
}
//if it had a constructor(blackboard)
try {
Object o1 = c.newInstance(o);
if (o1 instanceof GComponentInterface) {
//load was successfull
return ((GComponentInterface) o1).getComponent(blackboard);
} else {
System.err.println("the class " + clazz + " doesn't implement the interface GComponentInterface, so it can't be put on the UI.");
}
} catch (InstantiationException e) {
System.err.println("There was an error while initializing the class" + clazz + "may be in it's constructor or in one of classes it instantiate in its constructor");
ExceptionHandler.catchException(e);
} catch (IllegalAccessException e) {
System.err.println("There was an error while initializing the class" + clazz + "may be in it's constructor or in one of classes it instantiate in its constructor");
ExceptionHandler.catchException(e);
} catch (InvocationTargetException e) {
System.err.println("There was an error while initializing the class" + clazz + "may be in it's constructor or in one of classes it instantiate in its constructor");
e.getTargetException().printStackTrace();
}
}
return null;
}
|
8297eb62-0ba8-41d5-b5f3-24ed07c95126
| 2
|
public void setTileCircuit2(float x, float y, int circuit, int inputID){
Vector2f temp = new Vector2f(x,y);
for(Tile tile : tileList ) {
if (TileUtil.getCoordinate(tile.getPosition()).equals(temp)){
tile.setCircuit(circuit);
tile.setInput(inputID);
}
}
}
|
5159fcdb-6bad-4d4c-83e9-3b03fc54540b
| 1
|
public void leaveUser(int userID) {
alstLeftUser.add(userID);
Match currentMatch = getCurrentMatch(userID);
if(currentMatch == null){
//
}else{
getCurrentMatch(userID).setLeftUser(alstLeftUser.toArray(new Integer[0]));
}
}
|
2d37389b-963f-4545-bbfa-6727db9e5efc
| 7
|
public boolean storeImageRGBFreqsToDb(String imageFileName, long[][][] rgbBin, long totalPixels) {
StopWatch sw = new StopWatch();
sw.start();
String insert_sql = "INSERT INTO filenames(filename) values(?)";
StringBuilder sql = new StringBuilder("INSERT INTO rgb_frequencies (id_image, r_value, g_value, b_value, frequency, frequency_perc) VALUES (?, ?, ?, ?, ?, ?)");
PreparedStatement ps_ins = null;
PreparedStatement ps = null;
try {
ps_ins = mySqlConfig.getConnection().prepareStatement(insert_sql, Statement.RETURN_GENERATED_KEYS);
ps_ins.setString(1, imageFileName);
ps_ins.executeUpdate();
ResultSet rs = ps_ins.getGeneratedKeys();
Integer rid = null;
if (rs.next()) {
rid = rs.getInt(1);
}else {
System.out.println("no resultset!");
}
ps = mySqlConfig.getConnection().prepareStatement(sql.toString());
for (int i = 0; i < 16; i++) {
for (int j = 0; j < 16; j++) {
for (int k = 0; k < 16; k++) {
ps.setInt(1, rid);
ps.setLong(2, i);
ps.setLong(3, j);
ps.setLong(4, k);
ps.setLong(5, rgbBin[i][j][k]);
double freq_perc = ((double) rgbBin[i][j][k]) / totalPixels;
ps.setDouble(6, freq_perc);
ps.addBatch();
}
}
}
ps.executeBatch();
} catch (SQLException ex) {
System.err.println(ex.getMessage());
return false;
} finally {
if (ps != null) {
try {
ps.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
sw.stop();
System.out.println("Inserting to DB took:" + sw.getTime() + " ms");
return true;
}
|
e3a30174-c802-41e0-861f-0945622afa3a
| 1
|
public void paivitaAukiolot(Aukiolo aukiolo) throws DAOPoikkeus {
// Avataan ensin tietokantayhteys
Connection yhteys = avaaYhteys();
try {
// Suoritetaan haku
// Alustetaan sql-lause
String sql = "UPDATE Aukiolot SET arkialku=?,arkiloppu=?,vklpalku=?,vklploppu=? WHERE aukioloID=1";
PreparedStatement lause = yhteys.prepareStatement(sql);
// Muunnetaan vielä Aukiolo-luokan oliosta saadut Date-muuttujat
// java.sql.Time -muotoisiksi.
java.sql.Time sqlArkialku = new java.sql.Time(aukiolo.getArkialku().getTime());
java.sql.Time sqlArkiloppu = new java.sql.Time(aukiolo.getArkiloppu().getTime());
java.sql.Time sqlVklpalku = new java.sql.Time(aukiolo.getVklpalku().getTime());
java.sql.Time sqlVklploppu = new java.sql.Time(aukiolo.getVklploppu().getTime());
// Täytetään puuttuvat tiedot SQL-lauseeseen
lause.setTime(1, sqlArkialku);
lause.setTime(2, sqlArkiloppu);
lause.setTime(3, sqlVklpalku);
lause.setTime(4, sqlVklploppu);
// Suoritetaan SQL-lause
lause.executeUpdate();
// Tulostetaan varmistus konsoliin
System.out.println("PÄIVITETTIIN AUKIOLOAJAT: ");
System.out.println("Ma-pe: " + sqlArkialku + " - " + sqlArkiloppu);
System.out.println("La-su: " + sqlVklpalku + " - " + sqlVklploppu);
} catch(Exception e) {
// Jos tapahtui jokin virhe...
throw new DAOPoikkeus("Aukioloaikojen päivittäminen aiheutti virheen", e);
} finally {
// Lopulta aina suljetaan yhteys!
suljeYhteys(yhteys);
}
}
|
9c20114e-38dc-4977-b9bc-fb0ccce9b7e9
| 7
|
public void inxbuild() {
int i, j, smallpos, smallval;
int[] p;
int[] q;
int previouscol, startpos;
previouscol = 0;
startpos = 0;
for (i = 0; i < netsize; i++) {
p = network[i];
smallpos = i;
smallval = p[1]; /* index on g */
/* find smallest in i..netsize-1 */
for (j = i + 1; j < netsize; j++) {
q = network[j];
if (q[1] < smallval) { /* index on g */
smallpos = j;
smallval = q[1]; /* index on g */
}
}
q = network[smallpos];
/* swap p (i) and q (smallpos) entries */
if (i != smallpos) {
j = q[0];
q[0] = p[0];
p[0] = j;
j = q[1];
q[1] = p[1];
p[1] = j;
j = q[2];
q[2] = p[2];
p[2] = j;
j = q[3];
q[3] = p[3];
p[3] = j;
}
/* smallval entry is now in position i */
if (smallval != previouscol) {
netindex[previouscol] = (startpos + i) >> 1;
for (j = previouscol + 1; j < smallval; j++)
netindex[j] = i;
previouscol = smallval;
startpos = i;
}
}
netindex[previouscol] = (startpos + maxnetpos) >> 1;
for (j = previouscol + 1; j < 256; j++)
netindex[j] = maxnetpos; /* really 256 */
}
|
e41ce477-3f2c-4817-94fe-24f6b9f44320
| 6
|
public int compareTo(TailString ts) {
for(int i=s.length()-1, j=ts.s.length()-1;; i--, j--)
if(i < 0) return j < 0 ? 0 : 1;
else if(j < 0) return -1;
else if(s.charAt(i) > ts.s.charAt(j)) return -1;
else if(s.charAt(i) < ts.s.charAt(j)) return 1;
}
|
ff724c1c-bd14-4532-ab44-2dec08ef361b
| 6
|
private void drawTetris( Graphics g, ImageObserver imgObserver ) {
// グリッドの描画
short[][] grid = _model.getGrid();
short[][] gridColor = _model.getGridColor();
for ( int y = 0; y < Game.GRID_Y; y++ ) {
for ( int x = 0; x < Game.GRID_X; x++ ) {
if (grid[ y ][ x ] == 1) {
g.drawImage(_model.getBlock(), ( x + 1 ) * Game.BLOCK_SIZE, y * Game.BLOCK_SIZE,
( x + 1 ) * Game.BLOCK_SIZE + Game.BLOCK_SIZE, y * Game.BLOCK_SIZE + Game.BLOCK_SIZE,
gridColor[ y ][ x ] * Game.BLOCK_SIZE, 0, gridColor[ y ][ x ] * Game.BLOCK_SIZE + Game.BLOCK_SIZE,
Game.BLOCK_SIZE, imgObserver);
}
}
}
// ブロックの描画
Block block = _model.getBlockObj();
for ( int y = 0; y < Block.MAX_Y; y++ ) {
for ( int x = 0; x < Block.MAX_X; x++ ) {
if ( block.getBlock()[ y ][ x ] == 1 ) {
g.drawImage(_model.getBlock(), ( block.getPos().x + 1 + x ) * Game.BLOCK_SIZE, ( block.getPos().y + y ) * Game.BLOCK_SIZE,
( block.getPos().x + 1 + x ) * Game.BLOCK_SIZE + Game.BLOCK_SIZE, ( block.getPos().y + y ) * Game.BLOCK_SIZE + Game.BLOCK_SIZE,
block.getImageNo() * Game.BLOCK_SIZE, 0, block.getImageNo() * Game.BLOCK_SIZE + Game.BLOCK_SIZE, Game.BLOCK_SIZE, imgObserver);
}
}
}
}
|
ceacd4b2-5f34-4d7f-ac9c-b3037a063b59
| 5
|
public Object match(final String path) {
if (rules.containsKey(path)) {
return rules.get(path);
}
int n = path.lastIndexOf('/');
for (Iterator it = lpatterns.iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (path.substring(n).endsWith(pattern)) {
return rules.get(pattern);
}
}
for (Iterator it = rpatterns.iterator(); it.hasNext();) {
String pattern = (String) it.next();
if (path.startsWith(pattern)) {
return rules.get(pattern);
}
}
return null;
}
|
8c560b31-7132-4fc4-b17f-3f3fbb0ec490
| 2
|
private void initializeCurrentTransition(IWorkbenchPartReference activePart) {
currentTransition = findTransitionContaining(activePart);
if(currentTransition == null)
currentTransition = findFirstNonEmptyTransition();
if(currentTransition == null)
currentTransition = transitions.get(0);
currentTransition.select(activePart);
}
|
38cdaa80-dae6-4a99-a694-6d6b74a5b211
| 7
|
@Override
public boolean equals(Object o )
{
if(o == null)
return false;
if(o == this)
return true;
if(!(o instanceof Fertigungsplan))
return false;
Fertigungsplan f = (Fertigungsplan)o;
if(f.nr != nr || f.id != id || f.auftragNr != auftragNr || f.bauteilNr != bauteilNr)
return false;
return true;
}
|
75e86042-95ef-4cf0-b77c-327745262df6
| 3
|
public void visitLdcInsn(final Object cst) {
mv.visitLdcInsn(cst);
if (constructor) {
pushValue(OTHER);
if (cst instanceof Double || cst instanceof Long) {
pushValue(OTHER);
}
}
}
|
954a8133-7f7b-4182-8734-705e54c381d6
| 2
|
public double standardizedAverageCorrelationCoefficientsWithTotals(){
if(!this.dataPreprocessed)this.preprocessData();
if(!this.covariancesCalculated)this.covariancesAndCorrelationCoefficients();
return this.standardizedMeanRhoWithTotals;
}
|
b2a9a3b8-4841-4a81-bcfb-f2f8d130113c
| 1
|
public static void main(String[] args) {
try {
ArchitectureUi dialog = new ArchitectureUi();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
|
42cff6aa-d2e2-4048-9f11-ee3c082fdaf7
| 5
|
protected static Object checkSurrounds(
Holding holding, int upgradeLevel, boolean verbose
) {
final boolean NV = ! verbose ;
float safety = 0 - holding.base().dangerMap.longTermVal(holding.origin()) ;
if (holding.stocks.amountOf(PRESSFEED) > 0.5f) safety += 1.5f ;
if (safety < SAFETY_NEEDS[upgradeLevel]) return NV ? NOT_MET :
"This area feels too unsettled for your subjects' comfort, hindering "+
"further investment in a life here." ;
float ambience = holding.world().ecology().ambience.valueAt(holding) ;
ambience += holding.extras().size() / 2f ;
if (ambience < AMBIENCE_NEEDS[upgradeLevel]) return NV ? NOT_MET :
"The aesthetics of the area could stand improvement before the "+
"residents will commit to improving their property." ;
return NEEDS_MET ;
}
|
e8cd8c26-5ebb-4c13-85f9-c4f12670451f
| 0
|
@Override
public int hashCode() {
return this.username.hashCode();
}
|
e3e510cd-561b-4e7a-8715-ee52d3ad8d86
| 2
|
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (taskId < 0) {
start();
}
}
}
|
52214458-d49c-4c57-b419-d9dfba563d29
| 8
|
private void handleFirstStageMessage(FirstStageMessage fsm) {
MnPeerState peerState = mnPeer.getPeerState();
if(! mnPeer.isMainPeer()) {
throw new Error("First stage message must be forwarded to main peer");
}
if(ssCache.contains(fsm.getMessageId())) {
// Can happen if a 1st stage message is re-sent
// to new main peer but was already received as 3rd stage message
printMessage("First stage message already received.");
return;
}
MessageId msgId = fsm.getMessageId();
ForwardType type = fsm.getForwardType();
Message m = fsm.getMessage();
printMessage("Received 1st stage message ("+type+") from "+fsm.getSender());
DAId senderId = fsm.getSender();
FirstStageAckMessage ack = new FirstStageAckMessage(senderId, msgId);
SecondStageWaitingAcks.Destinations dest = new SecondStageWaitingAcks.Destinations(peerState.getMaxNumOfChildren());
SourceMn src = new SourceMn();
src.setThis();
SecondStageMessageInfo msgInf = new SecondStageMessageInfo(msgId,
type, src, m);
if(type.equals(ForwardType.toLeader)) {
if(peerState.hasParent()) {
sendSecondStageMessageToParent(dest, msgInf);
} else {
// message reached destination
m.setSender(mnPeer.getDistributedAgent().getDaId());
m.setRecipient(mnPeer.getDistributedAgent().getDaId());
if(m instanceof MnTreeMessage) {
MnTreeMessage mtm = (MnTreeMessage) m;
mtm.setSenderMn(peerState.getThisMnId());
mtm.setRecipientMn(peerState.getThisMnId());
}
mnPeer.getCommunicator().submitIncomingMessage(m);
// Send first stage ack
com.sendDatagramMessage(ack);
return;
}
} else if(type.equals(ForwardType.broadcast)) {
sendSecondStageMessageToParent(dest, msgInf);
sendSecondStageMessageToChildren(dest, -1, msgInf);
} else {
throw new Error("Unhandled forward type");
}
ThirdStageWaitingAcks.Destinations tDest = new ThirdStageWaitingAcks.Destinations();
sendThirdStageMessages(tDest, msgInf);
ssCache.cache(msgInf);
ssWaitingAck.waitForAcks(dest, msgId);
fsWaitingAck.waitAck(msgId, ack);
tsWaitingAck.waitForAcks(tDest, msgId);
printMessage("2nd cache size: "+ssCache.size());
if(type.equals(ForwardType.broadcast)) {
// Message reached destination
m.setSender(mnPeer.getDistributedAgent().getDaId());
m.setRecipient(mnPeer.getDistributedAgent().getDaId());
if(m instanceof MnTreeMessage) {
MnTreeMessage mtm = (MnTreeMessage) m;
mtm.setSenderMn(peerState.getThisMnId());
mtm.setRecipientMn(peerState.getThisMnId());
}
mnPeer.getCommunicator().submitIncomingMessage(m);
} // else type == toLeader : already handled
}
|
6a9275ea-8569-4c48-a093-d74abd8a2d91
| 6
|
public void Collision()
{
Actor collision1 = getOneIntersectingObject(Spikyball2.class);
Actor collision2 = getOneIntersectingObject(Spikyball3.class);
Actor collision3 = getOneIntersectingObject(Ghost.class);
if(collision1 != null)//if you have not run into it
{
World myWorld = getWorld();
JavaBackground space = (JavaBackground)myWorld;
HealthBar healthbar = space.getHealthBar();
if(touchingSpikyBall2 == false)
if(touchingSpikyBall3 == false)
{
healthbar.loseHealth();
touchingSpikyBall2 = true;
touchingSpikyBall3 = true;
if(healthbar.health <=0)
{
myWorld.removeObject(this);
}
}
counter.add(1);
Greenfoot.playSound("hooray.wav");
}else {
touchingSpikyBall2 = false;
touchingSpikyBall3 = false;
if(collision2 != null)//if you have not run into it
{
counter.add(1);
Greenfoot.playSound("explosion.wav");
}
if(collision3 != null)//if you have not run into it
{
counter.add(1);
Greenfoot.playSound("fanfare.wav");
}
}
}
|
ef76afdd-f523-49ee-9604-81834d7ba5a6
| 4
|
public void increaseKey(int i, Key key) {
if (i < 0 || i >= NMAX) throw new IndexOutOfBoundsException();
if (!contains(i)) throw new NoSuchElementException("index is not in the priority queue");
if (keys[i].compareTo(key) >= 0) throw new IllegalArgumentException("Calling increaseKey() with given argument would not strictly increase the key");
keys[i] = key;
sink(qp[i]);
}
|
c1daba42-6956-401b-9d74-f0cc1804dc71
| 7
|
public EPConnectablesDialog(ElementPanel panel, Component ele) {
this.setTitle("Input Connectors");
this.setModal(true);
for (Component e : panel.getElements()) {
if (e == ele)
continue;
if (e instanceof InputStub)
continue;
for (Connector c : e.getConnectors()) {
if (c instanceof InputConnector)
if (!((InputConnector) c).isConnected())
connectables.add((InputConnector) c);
}
}
add(getCtlPanel(), BorderLayout.SOUTH);
if (connectables.size() > 0) {
cb = new JList(connectables.toArray(new Connector[connectables
.size()]));
cb.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
cb.setSelectedIndex(0);
add(new JScrollPane(cb));
} else {
okBtn.setEnabled(false);
JPanel ip = new JPanel();
ip.setLayout(new BorderLayout());
ip.setPreferredSize(new Dimension(300, 200));
ip.add(new JLabel("No avaliable connectors", JLabel.CENTER));
add(ip);
}
this.setDefaultCloseOperation(JDialog.DO_NOTHING_ON_CLOSE);
pack();
this.setLocationRelativeTo(null);
}
|
ab917d06-e591-47dc-9096-a6155da6c17f
| 1
|
public CtClass makeClassIfNew(InputStream classfile)
throws IOException, RuntimeException
{
compress();
classfile = new BufferedInputStream(classfile);
CtClass clazz = new CtClassType(classfile, this);
clazz.checkModify();
String classname = clazz.getName();
CtClass found = checkNotExists(classname);
if (found != null)
return found;
else {
cacheCtClass(classname, clazz, true);
return clazz;
}
}
|
d51f7b43-448d-4b62-b66d-415eef5b616c
| 8
|
public void XbIDX9 (int n, int Dir, String Step2){
String ff;
int ln;
switch(n)
{
case 0:
Step2 = Step2.replace("xb", "E0");
ff = Integer.toHexString(Dir);
ln = ff.length();
if(ln == 1)
ff = "0" + ff;
Step2 = Step2.replace("ff", ff);
machCod2.add(Step2);
break;
case 1:
Step2 = Step2.replace("xb", "E8");
ff = Integer.toHexString(Dir);
ln = ff.length();
if(ln == 1)
ff = "0" + ff;
Step2 = Step2.replace("ff", ff);
machCod2.add(Step2);
break;
case 2:
Step2 = Step2.replace("xb", "F0");
ff = Integer.toHexString(Dir);
ln = ff.length();
if(ln == 1)
ff = "0" + ff;
Step2 = Step2.replace("ff", ff);
machCod2.add(Step2);
break;
case 3:
Step2 = Step2.replace("xb", "F8");
ff = Integer.toHexString(Dir);
ln = ff.length();
if(ln == 1)
ff = "0" + ff;
Step2 = Step2.replace("ff", ff);
machCod2.add(Step2);
break;
default:
break;
}
}
|
96d5160d-2fb6-424e-bf55-9994318565d5
| 9
|
protected PseudoSequencePair getFirstInstanceOfPrefixSequenceNEW(List<Itemset> prefix, int i){
int remainingToMatchFromPrefix = i;
List<Position> listPositions = new ArrayList<Position>();
int prefixItemsetPosition = 0;
// for each itemset of sequence
for(int j=0; j< size(); j++){
int itemInPrefixPosition =0;
boolean allMatched = false;
int searchedItem = prefix.get(prefixItemsetPosition).get(itemInPrefixPosition);
List<Position> tempList = new ArrayList<Position>();
// for each item in itemset
for(int k=0; k < getSizeOfItemsetAt(j) && !allMatched; k++) {
int currentItem = getItemAtInItemsetAt(k, j);
if(currentItem == searchedItem) {
tempList.add(new Position(j, k));
itemInPrefixPosition++;
if(itemInPrefixPosition == prefix.get(prefixItemsetPosition).size() || tempList.size() == remainingToMatchFromPrefix) {
allMatched = true;
break;
}
searchedItem = prefix.get(prefixItemsetPosition).get(itemInPrefixPosition);
}else if(currentItem > searchedItem) {
break;
}
}
if(allMatched) {
remainingToMatchFromPrefix -= tempList.size();
listPositions.addAll(tempList);
prefixItemsetPosition++;
if(prefixItemsetPosition == prefix.size()) {
PseudoSequenceBIDE newSequence = new PseudoSequenceBIDE(this, this.firstItemset, this.firstItem,
listPositions.get(i-1).itemset, listPositions.get(i-1).item);
return new PseudoSequencePair(newSequence, listPositions);
}
}
}
return null; // should not happen
}
|
e3648037-76f4-4eb8-8b47-80c509d9b043
| 7
|
public static Stella_Object inlinableMethodBody(MethodSlot method) {
{ Cons definition = null;
Stella_Object body = KeyValueList.dynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_CACHED_INLINABLE_METHOD_BODY, null);
if (body == method) {
return (null);
}
if (body != null) {
return (body);
}
definition = ((Cons)(Stella.unstringifyStellaSource(method.methodStringifiedSource, method.homeModule())));
Cons.extractOptions(definition, null);
KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_CACHED_INLINABLE_METHOD_BODY, method, null);
if (definition.length() == 4) {
body = definition.last();
if (Stella_Object.safePrimaryType(body) == Stella.SGT_STELLA_CONS) {
{ Cons body000 = ((Cons)(body));
if ((body000.value == Stella.SYM_STELLA_RETURN) &&
(Stella_Object.verbatimTreeP(body000.rest.value) ||
(!Stella_Object.searchConsTreeP(body000, Stella.SYM_STELLA_VERBATIM)))) {
return (KeyValueList.setDynamicSlotValue(method.dynamicSlots, Stella.SYM_STELLA_CACHED_INLINABLE_METHOD_BODY, Stella_Object.permanentifyForm(body000.rest.value), null));
}
}
}
else {
}
}
return (null);
}
}
|
944391ed-1ce4-4f0d-939a-e079f52187a3
| 0
|
public void setCitta(String citta) {
this.citta = citta;
}
|
7ee111ca-c28c-4482-a929-017e52290f30
| 9
|
public PersistenceDelegate getPersistenceDelegate(Class<?> type) {
if (type == null) {
return nullPD; // may be return a special PD?
}
// registered delegate
PersistenceDelegate registeredPD = delegates.get(type);
if (registeredPD != null) {
return registeredPD;
}
if (type.getName().startsWith(
UtilCollectionsPersistenceDelegate.CLASS_PREFIX)) {
return utilCollectionsPD;
}
if (type.isArray()) {
return arrayPD;
}
if (Proxy.isProxyClass(type)) {
return proxyPD;
}
// check "persistenceDelegate" property
try {
BeanInfo beanInfo = Introspector.getBeanInfo(type);
if (beanInfo != null) {
PersistenceDelegate pd = (PersistenceDelegate) beanInfo
.getBeanDescriptor().getValue("persistenceDelegate"); //$NON-NLS-1$
if (pd != null) {
return pd;
}
}
} catch (Exception e) {
// Ignored
}
// default persistence delegate
return defaultPD;
}
|
e7e79510-82cd-47ae-a6ca-f4cf6c147385
| 7
|
public int toInt(Piece p){
if(p.toString().charAt(1)== 'P')
return 1;
if(p.toString().charAt(1)=='N')
return 3;
if(p.toString().charAt(1)=='B')
return 4;
if(p.toString().charAt(1)== 'R')
return 5;
if(p.toString().charAt(1)== 'Q')
return 9;
if(p.toString().charAt(1)== 'K')
return 50;
if(p.toString().charAt(1)== 'X')
return 0;
return 0;
}
|
32d82d1d-2025-43d0-a2b2-f5eb2fd75092
| 1
|
public void stop() {
// Note: writePointer will be one ahead of the last message byte, so
// we can read it as size in this case
byte[] message = new byte[writePointer];
for(int i = 0; i < writePointer; i++) {
message[i] = currentMessage[i];
}
synchronized(messageBuffer) {
messageBuffer.add(message);
}
// No need to replace currentMessage,
// new payload will simply replace it.
writePointer = 0;
}
|
46749be5-7393-4b1d-99a7-559bc4dcff9d
| 6
|
public static void main(String[] argv) {
try {
// Retrieve a character in a Xml file
Character character = XmlMarshaller.unMarshallCharacter();
// Default localhost host and default port 1099 is used by RMI
Registry registry = LocateRegistry.getRegistry();
Registry registry2 = LocateRegistry.getRegistry(1100);
// Getting the remote object
IClientRMIObject clientRemoteObject = (IClientRMIObject) registry.lookup("IClientRMIObject");
// 1 : Set a map according to the type specified by the client
clientRemoteObject.setMapForGeneration(MapTypeEnum.WAREHOUSE);
// 2 : Set the character to play with
boolean isCharacterSet = clientRemoteObject.setCharacterToPlayWith(character);
if (!isCharacterSet) {
logger.log(Level.SEVERE, "Server was not able to set character");
}
// 3 : Set game parameters
HashMap<ParameterEnum, Integer> parameterMap = new HashMap<>();
parameterMap.put(ParameterEnum.DIFFICULTY_PERCENTAGE, 50);
parameterMap.put(ParameterEnum.MONTER_PERCENTAGE, 26);
parameterMap.put(ParameterEnum.MONSTER_DIFFICULTY_PERCENTAGE, 25);
parameterMap.put(ParameterEnum.MAP_SIZE_INTEGER, 5);
clientRemoteObject.setParameters(parameterMap);
// Send a message to the engine
try {
byte[] buffer = "CLIENT_ENTITY_READY".getBytes();
DatagramPacket packetSent = new DatagramPacket(buffer, buffer.length, InetAddress.getLocalHost(), 8080);
DatagramSocket datagramSocket = new DatagramSocket();
datagramSocket.send(packetSent);
datagramSocket.close();
} catch (SocketException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// Register for callback
Boolean isGameOver = new Boolean(false);
IEngineRMICallback iEngineRMICallback = (IEngineRMICallback) registry2.lookup("IEngineRMICallback");
IClientRMICallback iClientRMICallback = new ClientRMICallback(isGameOver);
iEngineRMICallback.registerForCallBack(iClientRMICallback);
// Main thread is waiting for the game to end
synchronized (isGameOver) {
try {
isGameOver.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("Game is now over");
iEngineRMICallback.unRegisterForCallBack(iClientRMICallback);
XmlMarshaller.marshallCharacter(clientRemoteObject.retrieveCharacterForMarshalling());
} catch (RemoteException e) {
e.printStackTrace();
} catch (NotBoundException e) {
e.printStackTrace();
}
}
|
d8daaaca-cfd0-4282-81a3-00a28aa79114
| 3
|
@Override
public void run(){
try{
System.out.println("waiting for worker join in");
while(true){
Socket workerSocket = serverSocket.accept();
System.out.println("worker: "+workerSocket.getInetAddress()+":"+workerSocket.getPort()+" join in");
manager.workersMap.put(workerCnt, workerSocket);
ManagerServer procServer = new ManagerServer(manager,workerCnt,workerSocket);
manager.processServerMap.put(workerCnt, procServer);
new Thread(procServer).start();
workerCnt++;
}
}catch(IOException e){
e.printStackTrace();
System.out.println("socket server accept failed");
}
try {
serverSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("socket Server failed to close");
}
}
|
d93a529b-eec2-4234-b437-f269f4a82dad
| 8
|
@Override
public void move(int x, int y, EPlayer player) {
try {
if (x >= 0 && x < super.getGameSize() && y >= 0 && y < super.getGameSize()) {
if (getField(x, y) == EField.Empty) {
super.move(x, y, player);
if(player == EPlayer.FirstPlayer && !super.isGameIsEnded()) super.autoTurn(EPlayer.SecondPlayer);
Core.getIntance().update();
} else
throw new ExceptionLog("Ошибка: попытка хода в занятое поле.");
} else
throw new ExceptionLog("Ошибка: попытка хода в поле, находящемся за пределами игровой сетки.");
} catch (ExceptionLog e) {
e.print();
}
}
|
a7c06513-71cf-4af6-b6f3-860a1eabbc91
| 4
|
@Override
public void mouseClicked(MouseEvent e) {
int sizeOfTile = this.getPreferredSize().height / drawingSize;
int x = e.getX();
int y = e.getY();
// convert coordinates to column and row
int i = (int) Math.floor((float) x / (float) sizeOfTile);
int j = (int) Math.floor((float) y / (float) sizeOfTile);
// flip color
if (i < drawingSize && j < drawingSize && i >= 0 && j >= 0) {
drawing[i][j] = (drawing[i][j] + 1) % 2;
}
repaint();
}
|
501ffede-5773-45ed-b0d0-e51db37e8ccc
| 7
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
SchoolOfficer that = (SchoolOfficer) o;
if (getType() != null ? !getType().equals(that.getType()) : that.getType() != null) return false;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
return true;
}
|
88b45bb9-a6d2-49e5-a492-21547b6273a1
| 6
|
private static boolean doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException {
if (destFile.exists() && destFile.isDirectory()) {
throw new IOException("Destination '" + destFile + "' exists but is a directory");
}
FileInputStream fis = null;
FileOutputStream fos = null;
FileChannel input = null;
FileChannel output = null;
try {
fis = new FileInputStream(srcFile);
fos = new FileOutputStream(destFile);
input = fis.getChannel();
output = fos.getChannel();
long size = input.size();
long pos = 0;
long count = 0;
while (pos < size) {
count = size - pos > FILE_COPY_BUFFER_SIZE ? FILE_COPY_BUFFER_SIZE : size - pos;
pos += output.transferFrom(input, pos, count);
}
} finally {
IOUtils.closeQuietly(output);
IOUtils.closeQuietly(fos);
IOUtils.closeQuietly(input);
IOUtils.closeQuietly(fis);
}
if (srcFile.length() != destFile.length()) {
throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'");
}
if (preserveFileDate) {
destFile.setLastModified(srcFile.lastModified());
}
return true;
}
|
878f5835-214e-4fbb-9d6e-5c1d80adb215
| 7
|
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(CommandViewList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(CommandViewList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(CommandViewList.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(CommandViewList.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() {
try {
new CommandViewList().setVisible(true);
} catch (SQLException ex) {
Logger.getLogger(CommandViewList.class.getName()).log(Level.SEVERE, null, ex);
}
}
});
}
|
c0a48334-d119-4ea3-ad21-0bbf5bf3aca5
| 2
|
public Car getRentedCars(){
for (Car car:CARS){
if(car.isCarRented() == true){
return car;
}
}
return null;
}
|
7633ade5-a39a-4690-8db9-e71072e775dc
| 9
|
public static int ifOne(int n){
if(n==1 || n==2 || n==6)
return 3;
else if(n==3 || n==7 || n==8)
return 5;
else if(n==4 || n==5 || n==9)
return 4;
else
return 0;
}
|
13ca8b55-016f-4e3a-84e1-d4de2ca3eeb0
| 6
|
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
if (this.getRoom() == null)
return false;
// if (this.getMovie() == null)
// return false;
if ( !(other instanceof Seance))
return false;
Seance otherSeance = (Seance) other;
if (otherSeance.getRoom() == null)
return false;
// if (otherSeance.getMovie() == null)
// return false;
return this.startDateTime.equals(otherSeance.getStartDateTime()) && this.room.equals(otherSeance.getRoom()) /*&& this.movie
.equals(otherSeance.getMovie()))*/;
}
|
abdbb210-c5b3-46b1-9539-90a2553e3c2d
| 2
|
public static int[] getValue(Integer key) {
for (Integer i : map.keySet()) {
if (i==key) {
return map.get(i);
}
}
return null;
}
|
fbc6c594-5b40-4402-9bb7-2fb3b6fae539
| 9
|
public final NiklausParser.variabledeclaration_return variabledeclaration() throws RecognitionException {
NiklausParser.variabledeclaration_return retval = new NiklausParser.variabledeclaration_return();
retval.start = input.LT(1);
CommonTree root_0 = null;
Token VAR24=null;
Token IDENTIFIER25=null;
Token COMMA26=null;
Token IDENTIFIER27=null;
Token COLON28=null;
Token TYPE29=null;
CommonTree VAR24_tree=null;
CommonTree IDENTIFIER25_tree=null;
CommonTree COMMA26_tree=null;
CommonTree IDENTIFIER27_tree=null;
CommonTree COLON28_tree=null;
CommonTree TYPE29_tree=null;
RewriteRuleTokenStream stream_COLON=new RewriteRuleTokenStream(adaptor,"token COLON");
RewriteRuleTokenStream stream_VAR=new RewriteRuleTokenStream(adaptor,"token VAR");
RewriteRuleTokenStream stream_COMMA=new RewriteRuleTokenStream(adaptor,"token COMMA");
RewriteRuleTokenStream stream_IDENTIFIER=new RewriteRuleTokenStream(adaptor,"token IDENTIFIER");
RewriteRuleTokenStream stream_TYPE=new RewriteRuleTokenStream(adaptor,"token TYPE");
try {
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:70:20: ( VAR IDENTIFIER ( COMMA IDENTIFIER )* COLON TYPE -> ^( VAR ( ^( TYPE IDENTIFIER ) )+ ) )
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:71:3: VAR IDENTIFIER ( COMMA IDENTIFIER )* COLON TYPE
{
VAR24=(Token)match(input,VAR,FOLLOW_VAR_in_variabledeclaration240);
stream_VAR.add(VAR24);
IDENTIFIER25=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_variabledeclaration242);
stream_IDENTIFIER.add(IDENTIFIER25);
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:71:18: ( COMMA IDENTIFIER )*
loop6:
do {
int alt6=2;
int LA6_0 = input.LA(1);
if ( (LA6_0==COMMA) ) {
alt6=1;
}
switch (alt6) {
case 1 :
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:71:19: COMMA IDENTIFIER
{
COMMA26=(Token)match(input,COMMA,FOLLOW_COMMA_in_variabledeclaration245);
stream_COMMA.add(COMMA26);
IDENTIFIER27=(Token)match(input,IDENTIFIER,FOLLOW_IDENTIFIER_in_variabledeclaration247);
stream_IDENTIFIER.add(IDENTIFIER27);
}
break;
default :
break loop6;
}
} while (true);
COLON28=(Token)match(input,COLON,FOLLOW_COLON_in_variabledeclaration251);
stream_COLON.add(COLON28);
TYPE29=(Token)match(input,TYPE,FOLLOW_TYPE_in_variabledeclaration253);
stream_TYPE.add(TYPE29);
// AST REWRITE
// elements: TYPE, IDENTIFIER, VAR
// token labels:
// rule labels: retval
// token list labels:
// rule list labels:
// wildcard labels:
retval.tree = root_0;
RewriteRuleSubtreeStream stream_retval=new RewriteRuleSubtreeStream(adaptor,"rule retval",retval!=null?retval.tree:null);
root_0 = (CommonTree)adaptor.nil();
// 72:3: -> ^( VAR ( ^( TYPE IDENTIFIER ) )+ )
{
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:72:6: ^( VAR ( ^( TYPE IDENTIFIER ) )+ )
{
CommonTree root_1 = (CommonTree)adaptor.nil();
root_1 = (CommonTree)adaptor.becomeRoot(
stream_VAR.nextNode()
, root_1);
if ( !(stream_TYPE.hasNext()||stream_IDENTIFIER.hasNext()) ) {
throw new RewriteEarlyExitException();
}
while ( stream_TYPE.hasNext()||stream_IDENTIFIER.hasNext() ) {
// C:\\Users\\Edward\\workspace\\ANTLRTest\\src\\Niklaus.g:72:12: ^( TYPE IDENTIFIER )
{
CommonTree root_2 = (CommonTree)adaptor.nil();
root_2 = (CommonTree)adaptor.becomeRoot(
stream_TYPE.nextNode()
, root_2);
adaptor.addChild(root_2,
stream_IDENTIFIER.nextNode()
);
adaptor.addChild(root_1, root_2);
}
}
stream_TYPE.reset();
stream_IDENTIFIER.reset();
adaptor.addChild(root_0, root_1);
}
}
retval.tree = root_0;
}
retval.stop = input.LT(-1);
retval.tree = (CommonTree)adaptor.rulePostProcessing(root_0);
adaptor.setTokenBoundaries(retval.tree, retval.start, retval.stop);
}
catch (RecognitionException re) {
reportError(re);
recover(input,re);
retval.tree = (CommonTree)adaptor.errorNode(input, retval.start, input.LT(-1), re);
}
finally {
// do for sure before leaving
}
return retval;
}
|
d5a485f1-ba92-41a8-836f-7479dc349043
| 1
|
public void addMany(int ...elements)//parameter can be more.
{
if(manyItems + elements.length > data.length)
{
ensureCapacity((manyItems + elements.length)*2);
}
System.arraycopy(elements, 0, data, manyItems, elements.length);
manyItems += elements.length;
}
|
f12ba254-9f68-477f-8b55-8d85a5d29f93
| 2
|
@Override
public void start() throws ConnectorLoadException {
if (twitterFactory != null)
throw new ConnectorLoadException("Invalid state; Twitter factory already declared.");
if (twitterToken != null)
throw new ConnectorLoadException("Invalid state; Twitter OAuth tokens already declared.");
twitterFactory = new TwitterFactory();
}
|
dafb8c2a-40c9-4578-9a77-f0a34ff21b15
| 6
|
@Override
protected void tick() {
Date currentDate = new Date();
double initialInterval = (double)(playerData.getUsedWeapon() - playerData.getstartCD());
double currentInterval = (double)(playerData.getUsedWeapon() - currentDate.getTime());
double percent = 1 - (currentInterval/initialInterval);
if(percent > 1) percent = 1;
if(percent < 0) percent = 0;
if(playerData.getSpoutCraftEnabled()) {
SpoutPlayer sPlayer = (SpoutPlayer) player;
Screen screen = sPlayer.getMainScreen();
int newWidth = (int)(50 * percent);
GenericGradient sGreenBar = (GenericGradient) screen.getWidget(playerData.getGreenBarId());
GenericGradient sRedBar = (GenericGradient) screen.getWidget(playerData.getRedBarId());
sGreenBar.setVisible(true);
sRedBar.setVisible(true);
sGreenBar.setWidth(newWidth);
sRedBar.setWidth(50 - sGreenBar.getWidth()).setX(sGreenBar.getWidth() - 25);
sGreenBar.setDirty(true);
sRedBar.setDirty(true);
if(percent >= 1) {
sGreenBar.setVisible(false);
sRedBar.setVisible(false);
sGreenBar.setWidth(0);
}
}
if(percent >= 1) {
if(!playerData.getSpoutCraftEnabled()) {
player.sendMessage(ChatColor.GREEN + "Ready to fight!");
}
this.cancel();
}
}
|
72d626d3-1151-426d-9fbf-e1ddc262da1c
| 7
|
protected void readImage() {
ix = readShort(); // (sub)image position & size
iy = readShort();
iw = readShort();
ih = readShort();
int packed = read();
lctFlag = (packed & 0x80) != 0; // 1 - local color table flag
interlace = (packed & 0x40) != 0; // 2 - interlace flag
// 3 - sort flag
// 4-5 - reserved
lctSize = 2 << (packed & 7); // 6-8 - local color table size
if (lctFlag) {
lct = readColorTable(lctSize); // read table
act = lct; // make local table active
} else {
act = gct; // make global table active
if (bgIndex == transIndex)
bgColor = 0;
}
int save = 0;
if (transparency) {
save = act[transIndex];
act[transIndex] = 0; // set transparent color if specified
}
if (act == null) {
status = STATUS_FORMAT_ERROR; // no color table defined
}
if (err())
return;
decodeImageData(); // decode pixel data
skip();
if (err())
return;
frameCount++;
// create new image to receive frame data
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB_PRE);
setPixels(); // transfer pixel data to image
frames.add(new GifFrame(image, delay)); // add image to frame list
if (transparency) {
act[transIndex] = save;
}
resetFrame();
}
|
b8d07281-ee06-469d-ac83-c82386bc7c6e
| 1
|
private void disconnectQuietly() {
synchronized(CONNECTION_LOCK) {
try {
//inform the server of the client's intent to disconnect
logger.finer("Sending disconnect packet");
sendPacket(Packet.createClientDisconnectPacket(clientId));
}
catch(CouldNotSendPacketException e) {
//ignore all exceptions--disconnecting gracefully isn't worth maintaining the connection
}
closeConnection();
}
}
|
0da30f9d-2bd1-443a-89ef-bc24703c6277
| 5
|
@Test
public void testRollbackFail2() throws InvalidProcessStateException, ProcessExecutionException,
InterruptedException, ExecutionException, ProcessRollbackException {
for (int i = 0; i < 25; i++) {
logger.debug(String.format("Run %s/25.", i + 1));
// test executing component (execution ongoing)
IProcessComponent<Void> decoratedComponent = TestUtil.rollbackFailComponent();
IProcessComponent<Void> busyComponent = new BusyComponent(decoratedComponent);
AsyncComponent<Void> ac = new AsyncComponent<Void>(busyComponent);
ac.execute(); // don't wait for completion
Future<?> future = null;
try {
future = ac.rollback();
} catch (InvalidProcessStateException | ProcessRollbackException ex) {
fail(ex.getMessage());
}
try {
future.get();
} catch (InterruptedException ex) {
fail(ex.getMessage());
} catch (ExecutionException ex) {
assertTrue(ex.getCause() instanceof ProcessRollbackException);
} finally {
assertTrue(ac.getState() == ProcessState.ROLLBACK_FAILED);
assertTrue(ac.getState() == decoratedComponent.getState());
}
}
}
|
92fefec5-b8f5-44aa-84bf-1028a90eb66b
| 9
|
public void displayData(List<Session> sessions, int trackCount) {
List<String> outputText = new ArrayList<String>();
Collections.sort(sessions);
String maxNetworkingTime = null;
Calendar cal = new GregorianCalendar();
SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mma");
Date d;
try {
d = dateFormat.parse(ConferenceConstraints.MorningStartTime);
cal.setTime(d);
dateFormat.setCalendar(cal);
String startTime;
int trackId = 1;
outputText.add("Track " + trackId);
for (Session s : sessions) {
for (Event e : s.getEvents()) {
startTime = dateFormat.format(cal.getTime());
if (e.getDescription().toLowerCase().contains("networking")
&& trackId > 1) {
outputText.add(maxNetworkingTime + " "
+ e.getDescription() + " " + e.getDuration()
+ "min");
} else {
outputText.add("" + dateFormat.format(cal.getTime())
+ " " + e.getDescription() + " "
+ e.getDuration() + "min");
}
cal.add(Calendar.MINUTE, e.getDuration());
if (e.getDescription().toLowerCase().contains("networking")
&& trackId < trackCount) {
if (trackId == 1) {
maxNetworkingTime = startTime;
}
trackId++;
outputText.add("Track " + trackId);
d = dateFormat
.parse(ConferenceConstraints.MorningStartTime);
cal.setTime(d);
}
}
}
for (String s : outputText) {
System.out.println(" " + s);
}
} catch (ParseException e) {
e.printStackTrace();
}
}
|
110ff90a-1115-47e3-8213-68f3075fe5f2
| 5
|
public static void main(String[] args) {
String urlStr = null;
while (true) {
try {
System.out.println("Enter url: ");
// read from standard input
BufferedReader reader = new BufferedReader(
new InputStreamReader(System.in));
// read a line of input from the keyboard until the ENTER key is
// pressed
urlStr = reader.readLine();
if (urlStr.length() == 0) {
System.out.println("No url specified: ");
continue;
}
System.out.println("Opening " + urlStr);
URL url = new URL(urlStr);
reader = new BufferedReader((new InputStreamReader(
url.openStream())));
System.out.println(reader.readLine());
reader.close();
} catch (MalformedURIException e) {
System.out.println("Invalid URL " + urlStr + ":"
+ e.getMessage());
} catch (IOException e) {
System.out.println("Unable to execute " + urlStr + ":"
+ e.getMessage());
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
|
1b7732e7-8675-446c-a317-b116be1332f4
| 4
|
public static Class<?> getActualType(final Field field) {
Type type = field.getGenericType();
if (type instanceof ParameterizedType) {
return (Class<?>)((ParameterizedType) type).getActualTypeArguments()[0];
}
if (field.getType().isArray()) {
return field.getType().getComponentType();
}
// Field type is a supported collection type but doesn't specify a contained objects
return null;
}
|
118dcd24-e49e-423a-a7c0-41e7057a69c7
| 9
|
public static void main(String[] args)
{
Fila aFila = new Fila(5); // criamos uma fila que comporta 5 itens
if (!aFila.isFull())
aFila.insert(10); // inserimos 4 itens
if (!aFila.isFull())
aFila.insert(20);
if (!aFila.isFull())
aFila.insert(30);
if (!aFila.isFull())
aFila.insert(40);
aFila.remove(); // removemos três itens (Repare que não falo quais itens ...obvio
aFila.remove(); // que será os 3 que entraram primeiro (10, 20, 30)
aFila.remove();
if (!aFila.isFull())
aFila.insert(50); // inserimos mais 4 itens!
if (!aFila.isFull())
aFila.insert(60); //
if (!aFila.isFull())
aFila.insert(70);
if (!aFila.isFull())
aFila.insert(80);
while( !aFila.isEmpty() ) // enquanto a fila não estiver vazia...
{
long n = aFila.remove(); // removemos os valores imprimindo-os!!!
System.out.print(n);
System.out.print(" ");
}
System.out.println("");
} // fim do método main
|
db27dea3-3585-4937-93ca-b31f99f55e41
| 0
|
public int getDepth()
{
return depth;
}
|
35303768-d3da-488f-953c-3ccab2696296
| 5
|
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || !(o instanceof HandTypesKey)) return false;
HandTypesKey that = (HandTypesKey) o;
if (getInt() != that.getInt()) return false;
if (getBoolean() != that.getBoolean()) return false;
return true;
}
|
1821a9f1-10d8-4226-af03-56e5cb63efe2
| 1
|
synchronized public static org.omg.CORBA.TypeCode type ()
{
if (__typeCode == null)
{
__typeCode = org.omg.CORBA.ORB.init ().create_interface_tc (HelloCorba.HelloHelper.id (), "Hello");
}
return __typeCode;
}
|
48078d86-820e-4888-88bd-713865c56093
| 3
|
private static Boolean toBoolean(String paramName, Object o, boolean required) throws BadConfig {
if (o == null) {
if (required)
throw new BadConfig("Parameter \"" + paramName + "\" is required");
return null;
}
if (!(o instanceof Boolean))
throw new BadConfig("In parameter \"" + paramName + "\", value \"" + o + "\" should be a boolean");
return (Boolean) o;
}
|
2432e12e-6e24-4072-8a8e-09aec1b7dd9e
| 8
|
@Override
public void processMessage(Privmsg privmsg) {
String[] parts = privmsg.getMessage().split(" ", 2);
int id = Integer.parseInt(parts[1]);
boolean state = false;
String action = "opened";
if (parts[0].charAt(1) == 'c') {
state = true;
action = "closed";
}
try {
if (pollDAO.setStatusOfPoll(id, state) > 0) {
privmsg.send("Poll #" + id + " " + action + ".");
if (action.equalsIgnoreCase("closed")) {
Future future = getFvb().pollFutures.get(id);
if (future != null) {
future.cancel(true);
}
} else if (action.equalsIgnoreCase("opened")) {
Future future = getFvb().pollFutures.get(id);
if (future != null) {
future.cancel(true);
}
Poll poll = pollDAO.getPoll(id);
if (poll.getExpiry() > System.currentTimeMillis()) {
PollExpiryAnnouncer announcer = new PollExpiryAnnouncer(poll.getExpiry(), poll.getId(), getFvb());
ScheduledFuture f = getFvb().pollExecutor.scheduleAtFixedRate(announcer, 5000L, 500L, TimeUnit.MILLISECONDS);
getFvb().pollFutures.put(id, f);
announcer.setFuture(f);
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
|
15b71c6c-d14f-4798-9bca-21a0f2a2ee77
| 6
|
static protected void UpdateLineColumn(char c)
{
column++;
if (prevCharIsLF)
{
prevCharIsLF = false;
line += (column = 1);
}
else if (prevCharIsCR)
{
prevCharIsCR = false;
if (c == '\n')
{
prevCharIsLF = true;
}
else
line += (column = 1);
}
switch (c)
{
case '\r' :
prevCharIsCR = true;
break;
case '\n' :
prevCharIsLF = true;
break;
case '\t' :
column--;
column += (8 - (column & 07));
break;
default :
break;
}
bufline[bufpos] = line;
bufcolumn[bufpos] = column;
}
|
661515c4-f7cf-40c3-9ce9-ec5041fadd31
| 1
|
public void visitStaticFieldExpr(final StaticFieldExpr expr) {
// C.f
// [declared field type] <= [C.f]
final MemberRef field = expr.field();
if (!expr.isDef()) {
start(expr, field.type());
}
}
|
1a65b364-93e7-4c06-8dda-7275d1caa5ac
| 6
|
public int minJumpsRecursive(int[] a, int l, int h) {
/* Base case: array of length 1*/
if (l == h) {
return 0;
}
/* Base case: if no jumps out of position i */
if (a[l] == 0) {
return Integer.MAX_VALUE;
}
/* Compute the minJumps from all j rechable from l; pick the min and add 1 */
int minJumps = Integer.MAX_VALUE;
for (int i = l + 1; i <= h && i <= l + a[l]; i++) {
System.out.printf("Computing: minJumps(%d)\n", i);
int jumps = minJumpsRecursive(a, i, h);
if (jumps != Integer.MAX_VALUE && jumps + 1 < minJumps) {
minJumps = jumps + 1;
}
}
return minJumps;
}
|
49be990e-4620-48e4-8152-a14ef81673c4
| 9
|
public void buildListModel() {
if(mapPanel.backdrop != null) {
listModel.addElement(mapPanel.backdrop.toString());
}
if(!mapPanel.backgroundMusic.matches("")) {
listModel.addElement(mapPanel.backgroundMusic);
}
if(mapPanel.player != null) {
listModel.addElement(mapPanel.player.toString());
}
if(!mapPanel.props.isEmpty()) {
for(int x = 0; x<mapPanel.props.size(); x++)
listModel.addElement(mapPanel.props.get(x).toString());
}
if(!MapPanel.actors.isEmpty()) {
for(int x = 0; x<MapPanel.actors.size(); x++)
listModel.addElement(MapPanel.actors.get(x).toString());
}
if(!mapPanel.paths.isEmpty()) {
for(int x = 0; x<mapPanel.paths.size(); x++)
listModel.addElement(mapPanel.paths.get(x).toString());
}
}
|
d573ab7f-f575-44a9-a287-9d17bf269748
| 1
|
@Override
public boolean accept(File file) {
// Allow only directories, or files with ".txt" extension
return file.isDirectory() || file.getAbsolutePath().endsWith(".asm");
}
|
2fb975e0-ecad-4f9c-9e5b-e9baa59453ae
| 1
|
private boolean jj_2_9(int xla) {
jj_la = xla; jj_lastpos = jj_scanpos = token;
try { return !jj_3_9(); }
catch(LookaheadSuccess ls) { return true; }
finally { jj_save(8, xla); }
}
|
13dc69ef-dc8e-4040-8cbf-9a46e8643a41
| 0
|
public Jason()
{
super("Jason", 8000, 300, 30, 80, as);
as.setSkill(0, "Poke", 30, 10, "Jason pokes his enemy lightly.");
as.setSkill(1, "Jab", 200, 60, "Jason jabs his enemy.");
as.setSkill(2, "Kick", 600, 100, "Jason kicks his enemy.");
as.setSkill(3, "Round-House Kick", 4500, 200, "Jason roundhouse kicks enemy in the face.");
}
|
ed8e1d27-ddf8-42c3-90fa-8360727c570d
| 1
|
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
java.security.cert.X509Certificate[] chain = null;
try {
TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
KeyStore tks = KeyStore.getInstance("JKS");
tks.load(this.getClass().getClassLoader().getResourceAsStream("SSL/serverstore.jks"),
SERVER_KEY_STORE_PASSWORD.toCharArray());
tmf.init(tks);
chain = ((X509TrustManager) tmf.getTrustManagers()[0]).getAcceptedIssuers();
} catch (Exception e) {
throw new RuntimeException(e);
}
return chain;
}
|
a7399a00-7a33-4c48-905c-ff6afd20e75e
| 2
|
public void setWeapon(Weapon weapon) {
weaponIndexDirty = true;
for (int i = 0; i < getWeaponsData().size(); i++) {
if (getWeaponsData().get(i).getWeapon().equals(weapon)) {
weaponIndex = i;
break;
}
}
}
|
c5bb749b-3ee9-45cd-b7f1-ba2c10719973
| 3
|
public boolean validateTransition(MoveMessageType move, Integer playerID) {
// Ueberpruefen ob das Reinschieben der Karte gueltig ist
Position sm = new Position(move.getShiftPosition());
if (!sm.isInsertablePosition() || sm.equals(forbidden)) {
System.err.println("Warning: verbotene Position der Schiebekarte");
return false;
}
Card sc = new Card(move.getShiftCard());
if (!sc.equals(shiftCard)) {
System.err
.println("Warning: Schiebekarte wurde illegal veraendert");
return false;
}
// Ueberpruefen ob der Spielzug gueltig ist
Board fake = this.fakeShift(move);
Position playerPosition = new Position(fake.findPlayer(playerID));
return fake.pathpossible(playerPosition, move.getNewPinPos());
}
|
2319a32e-6dce-49da-a48a-967fa10c1542
| 6
|
public static int maxSinglePathSum(TreeNode root, List<Integer> max) {
if (null == root) return 0;
int left = maxSinglePathSum(root.left, max);
int right = maxSinglePathSum(root.right, max);
int m = root.val;
m = m < left + root.val ? left + root.val : m;
m = m < right + root.val ? right + root.val : m;
m = m < left + root.val + right ? left + root.val + right : m;
max.add(m);
int res = root.val;
res = res < left + root.val ? left + root.val : res;
res = res < right + root.val ? right + root.val : res;
return res;
}
|
d18e60c1-bc4d-4627-a8db-15894671b18e
| 3
|
public Object getValueAt(int row, int col) {
if(row>-1 && col>-1 && data!=null)
return data[row][col];
else
return null;
}
|
e422aa86-7fb9-4552-9d52-3e1d0b07e695
| 5
|
private void pop(char c) throws JSONException {
if (this.top <= 0) {
throw new JSONException("Nesting error.");
}
char m = this.stack[this.top - 1] == null ? 'a' : 'k';
if (m != c) {
throw new JSONException("Nesting error.");
}
this.top -= 1;
this.mode = this.top == 0
? 'd'
: this.stack[this.top - 1] == null
? 'a'
: 'k';
}
|
c0a9a1be-40f8-4451-8c85-6971989ef1f2
| 0
|
public void removePropertyChangeListener(PropertyChangeListener listener) {
propertyChangeSupport.removePropertyChangeListener(listener);
}
|
f518edb8-9970-4775-ad36-786c34fd269d
| 6
|
public void checkPawn(){
if(color=='W'){
for(int i=0;i<8;i++){
if(aiarr[i][0].toString().charAt(1)=='P'){
aiarr[i][0]=new Queen(true);
}
}
}
if(color=='B'){
for(int i=0;i<8;i++){
if(aiarr[i][7].toString().charAt(1)=='P'){
aiarr[i][7]=new Queen(false);
}
}
}
}
|
ebf9f3eb-dc21-410a-b5b8-9d28b3f53807
| 6
|
@Override
public int compareTo(TimeSeriesKey other) {
/*System.out.println("In Compareto.......");
if( this.kpi.compareTo(other.getKpi())!=0){ // compare keys
return this.kpi.compareTo(other.getKpi());
}else if (this.time.compareTo(other.getTimestamp())!=0){ //If KPI's are the same then order by time
return (this.time.compareTo(other.getTimestamp()));
}else{
return 0;
}*/
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(0);
cal.setTime(this.time);
Calendar cal2 = Calendar.getInstance();
cal2.setTimeInMillis(0);
cal2.setTime(other.getTimestamp());
System.out.println("TimeSeriesKeyDaily In Compareto--" + cal.getTime().toString() + " --" + cal2.getTime().toString() );
int i=cal.get(Calendar.YEAR)- cal2.get(Calendar.YEAR);
if(i!=0) return ( i > 0 ? 1 :-1);
System.out.println("In Compareto Year is same");
i=cal.get(Calendar.MONTH)-cal2.get(Calendar.MONTH) ;
if(i!=0) return ( i > 0 ? 1 :-1);
System.out.println("In Compareto Month is same");
i=cal.get(Calendar.DAY_OF_MONTH)- cal2.get(Calendar.DAY_OF_MONTH);
return ( i > 0 ? 1 : (i < 0 ? -1:0));
}
|
322ff2ad-85a1-42ca-b699-4e7055f37d9b
| 0
|
public String getTax(){ return taxAdapter.getTaxes("20"); }
|
012c5a19-163f-405d-b623-548c138d5fac
| 2
|
public void leftMultiplyBy(Matrix that) {
double[][] values = new double[3][3];
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
values[i][j] = that.m[i][0] * this.m[0][j] + that.m[i][1]
* this.m[1][j] + that.m[i][2] * this.m[2][j];
setComponents(values);
}
|
b7e9d88f-304e-4875-8c62-f92d4ca6bc50
| 3
|
@Override
public List<ProductModel> getProductByName(String productName)
throws WebshopAppException {
if (productName != null) {
try (Connection conn = getConnection()) {
String sql = "SELECT * FROM products WHERE name = ?";
try (PreparedStatement pstmt = conn.prepareStatement(sql)) {
setString(pstmt, 1, productName);
try (ResultSet rs = pstmt.executeQuery()) {
List<ProductModel> foundProducts = new ArrayList<>();
while (rs.next()) {
foundProducts.add(parseModel(conn, rs));
}
Log.logOut(LOGGER, this, "GET_PRODUCT_BY_NAME",
"Found products: ", foundProducts.toString());
return foundProducts;
}
}
} catch (SQLException e) {
WebshopAppException excep = new WebshopAppException(e, this
.getClass().getSimpleName(), "GET_PRODUCT_BY_NAME");
Log.logOutWAException(LOGGER, excep);
throw excep;
}
}
return new ArrayList<ProductModel>();
}
|
69a5f2dd-8680-4888-b372-ccd49aae0a2c
| 9
|
void render(Graphics2D g, Object p, boolean b) {
if (!renderable)
return;
double x = 0, y = 0, grx = -5.0, gry = -5.0, gd = 10.0;
if (p instanceof GayBerneParticle) {
GayBerneParticle gb = (GayBerneParticle) p;
x = gb.rx;
y = gb.ry;
grx += x - 0.2 * gb.breadth;
gry += y - 0.2 * gb.breadth;
gd += 0.4 * gb.breadth;
}
else if (p instanceof Atom) {
Atom a = (Atom) p;
x = a.rx;
y = a.ry;
grx += x - 0.5 * a.sigma;
gry += y - 0.5 * a.sigma;
gd += a.sigma;
}
else if (p instanceof RectangularObstacle) {
RectangularObstacle obs = (RectangularObstacle) p;
x = obs.x + 0.5 * obs.width;
y = obs.y + 0.5 * obs.height;
grx += x - 10;
gry += y - 10;
gd += 20;
}
if (p instanceof ModelComponent) {
g.setColor(((MDView) ((ModelComponent) p).getHostModel().getView()).contrastBackground());
}
g.setStroke(b ? ViewAttribute.THIN : ViewAttribute.THIN_DASHED);
g.drawOval((int) grx, (int) gry, (int) gd, (int) gd);
g.drawOval((int) (x - 4), (int) (y - 4), 8, 8);
int vx1 = (int) (grx + 0.5 * gd);
int vy1 = (int) (gry - 2.5);
int vy2 = (int) (gry + gd + 2.5);
int hx1 = (int) (grx - 2.5);
int hy1 = (int) (gry + 0.5 * gd);
int hx2 = (int) (grx + gd + 2.5);
g.drawLine(vx1, vy1, vx1, vy2);
g.drawLine(hx1, hy1, hx2, hy1);
g.drawLine(hx1 + 2, vy1 + 2, hx2 - 2, vy2 - 2);
g.drawLine(hx1 + 2, vy2 - 2, hx2 - 2, vy1 + 2);
if (!b)
return;
if (mode == FORCE_MODE && u > 0) {
double finc = 0.5 * gd + Math.log(gear) * 10;
double endx = x + finc * costheta;
double endy = y + finc * sintheta;
double arrowx = 1.0 * costheta;
double arrowy = 1.0 * sintheta;
g.setStroke(ViewAttribute.MODERATE);
g.drawLine((int) x, (int) y, (int) endx, (int) endy);
grx = 5 * (arrowx * COS45 + arrowy * SIN45);
gry = 5 * (arrowy * COS45 - arrowx * SIN45);
g.drawLine((int) endx, (int) endy, (int) (endx - grx), (int) (endy - gry));
grx = 5 * (arrowx * COS45 - arrowy * SIN45);
gry = 5 * (arrowy * COS45 + arrowx * SIN45);
g.drawLine((int) endx, (int) endy, (int) (endx - grx), (int) (endy - gry));
}
}
|
88818782-0033-4db7-b37a-ee4d6a1151b4
| 4
|
protected void computeCoordinates() {
final double innerRadiusValue = innerRadius.get();
final double startAngleValue = startAngle.get();
final double length = this.length.get();
final double graphicAngle = startAngleValue + (length / 2.0);
final double radiusValue = radius.get();
final double graphicRadius = innerRadiusValue
+ (radiusValue - innerRadiusValue) / 2.0;
final double offsetValue = offset.get();
if (!clockwise.get()) {
innerStartX = innerRadiusValue
* Math.cos(Math.toRadians(startAngleValue));
innerStartY = -innerRadiusValue
* Math.sin(Math.toRadians(startAngleValue));
innerEndX = innerRadiusValue
* Math.cos(Math.toRadians(startAngleValue + length));
innerEndY = -innerRadiusValue
* Math.sin(Math.toRadians(startAngleValue + length));
innerSweep = false;
startX = radiusValue
* Math.cos(Math.toRadians(startAngleValue + length));
startY = -radiusValue
* Math.sin(Math.toRadians(startAngleValue + length));
endX = radiusValue * Math.cos(Math.toRadians(startAngleValue));
endY = -radiusValue * Math.sin(Math.toRadians(startAngleValue));
sweep = true;
if (graphic.get() != null) {
graphicX = graphicRadius
* Math.cos(Math.toRadians(graphicAngle))
- graphic.get().getBoundsInParent().getWidth() / 2.0;
graphicY = -graphicRadius
* Math.sin(Math.toRadians(graphicAngle))
- graphic.get().getBoundsInParent().getHeight() / 2.0;
}
translateX = offsetValue
* Math.cos(Math.toRadians(startAngleValue + (length / 2.0)));
translateY = -offsetValue
* Math.sin(Math.toRadians(startAngleValue + (length / 2.0)));
} else if (clockwise.get()) {
innerStartX = innerRadiusValue
* Math.cos(Math.toRadians(startAngleValue));
innerStartY = innerRadiusValue
* Math.sin(Math.toRadians(startAngleValue));
innerEndX = innerRadiusValue
* Math.cos(Math.toRadians(startAngleValue + length));
innerEndY = innerRadiusValue
* Math.sin(Math.toRadians(startAngleValue + length));
innerSweep = true;
startX = radiusValue
* Math.cos(Math.toRadians(startAngleValue + length));
startY = radiusValue
* Math.sin(Math.toRadians(startAngleValue + length));
endX = radiusValue * Math.cos(Math.toRadians(startAngleValue));
endY = radiusValue * Math.sin(Math.toRadians(startAngleValue));
sweep = false;
if (graphic.get() != null) {
graphicX = graphicRadius
* Math.cos(Math.toRadians(graphicAngle))
- graphic.get().getBoundsInParent().getWidth() / 2.0;
graphicY = graphicRadius
* Math.sin(Math.toRadians(graphicAngle))
- graphic.get().getBoundsInParent().getHeight() / 2.0;
}
translateX = offsetValue
* Math.cos(Math.toRadians(startAngleValue + (length / 2.0)));
translateY = offsetValue
* Math.sin(Math.toRadians(startAngleValue + (length / 2.0)));
}
}
|
bda9ec93-7aec-4ec2-a7ac-a9a14a18d210
| 0
|
public Result(PropertyTree firstMatchingNode) {
super();
nodes=new ArrayList<PropertyTree>(1);
nodes.add(firstMatchingNode);
}
|
5e65c1c4-5d5f-4047-9a27-67054af0d00b
| 3
|
public void use(BattleFunction iface, PokeInstance user, PokeInstance target, Move move) {
PokeInstance p;
if (this.target == Target.target) {
p = target;
} else {
p = user;
}
p.battleStatus.flags[flag] = false;
if (text != null) {
text = text.replace("$target", p.getName());
if (p.battleStatus.lastMove != -1)
text = text.replace("$lastMove", p.getMove(p.battleStatus.lastMove).getName());
iface.print(text);
}
}
|
6a4f8574-f2c4-4f8d-8ce2-b89a082921b9
| 2
|
public void sort(double[] input) {
int N = input.length;
for (int sz = 2; sz < N*2; sz *= 2) {
for (int lo = 0; lo < N; lo += sz) {
int hi = Math.min(lo + sz, N);
int mid = lo + sz / 2;
MergeSort.merge(input, lo, mid, hi);
}
}
}
|
f8df1a94-64b0-4769-ab97-ca1518890c52
| 6
|
public int match_main(String text, String pattern, int loc) {
// Check for null inputs.
if (text == null || pattern == null) {
throw new IllegalArgumentException("Null inputs. (match_main)");
}
loc = Math.max(0, Math.min(loc, text.length()));
if (text.equals(pattern)) {
// Shortcut (potentially not guaranteed by the algorithm)
return 0;
} else if (text.length() == 0) {
// Nothing to match.
return -1;
} else if (loc + pattern.length() <= text.length()
&& text.substring(loc, loc + pattern.length()).equals(pattern)) {
// Perfect match at the perfect spot! (Includes case of null pattern)
return loc;
} else {
// Do a fuzzy compare.
return match_bitap(text, pattern, loc);
}
}
|
29b5a8e3-01db-48b1-b895-a3ff254d8f50
| 9
|
public void processWeatherMultiplierConfiguration() throws ConfigurationException {
final String NO_WEATHER_STATION = "ERROR: cannot have weather_multiplier values without a weatherstation configured";
// If any of the multiplier values are configured then try and process a multiplier
// configuration.
if ((config.getProperty("weather_multiplier_value") != null)
|| (config.getProperty("weather_multiplier_max_temp") != null)
|| (config.getProperty("weather_multiplier_days_to_look_ahead") != null)) {
// Must have a weather station to look at weather values
if (weatherStations.isEmpty()) {
throw new ConfigurationException(NO_WEATHER_STATION);
}
// Check that ALL values have been populated for the weather multiplier.
try {
weatherMultiplierValue = Math.abs(Double.parseDouble(config
.getProperty("weather_multiplier_value")));
} catch (final NumberFormatException e) {
throw new ConfigurationException(
"ERROR: must supply a valid weather_multiplier_value value");
}
try {
final String maxTemp = config.getProperty("weather_multiplier_max_temp");
final String delimiter = maxTemp.substring(maxTemp.length() - 1);
maxTempThresholdInCelcius = Double.parseDouble(maxTemp.substring(0, maxTemp.length() - 1));
if (delimiter.equalsIgnoreCase("F")) {
maxTempThresholdInCelcius = (maxTempThresholdInCelcius - 32) * (5.0 / 9.0);
} else if (!delimiter.equalsIgnoreCase("C")) {
throw new ConfigurationException(
"ERROR: must supply a delimiter of \"C\" or \"F\" to weather_multiplier_max_temp");
}
weatherMultiplierMaxTemp = maxTempThresholdInCelcius;
} catch (final NumberFormatException e) {
throw new ConfigurationException(
"ERROR: must supply a valid weather_multiplier_max_temp value");
}
try {
weatherMultiplierDaysToLookAhead = Math.abs(Integer.parseInt(config
.getProperty("weather_multiplier_days_to_look_ahead")));
} catch (final NumberFormatException e) {
throw new ConfigurationException(
"ERROR: must supply a valid weather_multiplier_days_to_look_ahead value");
}
}
}
|
1a2441d4-aa36-4fc8-aca1-e98b870003d9
| 6
|
public static boolean checkHeader(ByteBuffer packet, int flag, int len, int id){
// (header s->c or c->s) [action flag | payload len | client id]
// (client id is 0 if client is sening connect request)
// parse packet
int buf_flag = packet.getInt(0);
int buf_len = packet.getInt(4);
int buf_id = packet.getInt(8);
// check fields for correctness
if ( buf_len != len ||
buf_flag > Constants.NUM_FLAGS ||
buf_flag < 0 ||
buf_len < 0 ||
buf_id != id) {
return false;
}
// check length field for correctness
if ((packet.capacity() - Constants.HEADER_LEN) != getPaddedLength(buf_len))
return false;
return true;
}
|
246451bb-6719-4239-89a0-58bcf44e4088
| 9
|
public static void addPrenotazioni(HttpServletRequest req, PrintWriter out) {
HttpSession s = req.getSession();
UserBean user = (UserBean) s.getAttribute("user");
String username = user.getUsername();
JSONArray jarr = null;
HashMap<String, Integer> carrello = new HashMap<>();
String data = req.getParameter("data").replace("T", " ");
try {
jarr = new JSONArray(req.getParameter("lista"));
for (int i = 0; i < jarr.length(); i++) {
JSONObject obj = jarr.getJSONObject(i);
String pizza = obj.getString("pizza");
Integer qt = obj.getInt("quantita");
if (carrello.containsKey(pizza)) {
qt += carrello.get(pizza);
}
carrello.put(pizza, qt);
}
Iterator<String> it = carrello.keySet().iterator();
while (it.hasNext()) {
String pizza = it.next();
Integer qt = carrello.get(pizza);
if (Model.getUtente(username).getPermission().equals("user")) {
int idUser = Model.getIdUtente(username);
int idPizza = Model.getIdPizza(pizza);
if (Model.getPizza(pizza) != null && qt > 0 && data != null && !data.equals("")) {
Prenotazione p = new Prenotazione(idUser, idPizza, qt, data);
Model.addPrenotazione(p);
} else {
errorMessage(s, "prenotazione non aggiunta");
}
}
}
} catch (JSONException | SQLException ex) {
Logger.getLogger(Controller.class.getName()).log(Level.SEVERE, null, ex);
}
}
|
002e72b9-db6c-437e-aee5-8a575ce010c3
| 2
|
public DefaultTokenizer() {
for (Operation op : Operation.values()) {
addOperation(op);
}
for (Function function : Function.values()) {
addFunction(function);
}
addConstant("pi", BigDecimal.valueOf(Math.PI));
addConstant("e", BigDecimal.valueOf(Math.E));
maps.add(constants);
maps.add(functions);
maps.add(operations);
}
|
657b5194-8b27-4318-a5a5-60c5a37d7d01
| 4
|
public void show(){ //Displays the Matching question.
Out.setDisp(2); //Set to Voice
Out.getDisp().renderLine(prompt);
String formL,formR; //Strings to hold left and right values to make formatting easier
for (int count = 1; count <= left.size() || count <= right.size(); count++){ //If either side still has elements, loop
if (count <= left.size()){ //If left side still has elements
formL = left.get(count-1) + ": "; //Set left formatting
}else formL = ""; //Blank out left side
if (count <= right.size()){ //If right side still has elements
formR = right.get(count-1); //Set right formatting
}else formR = ""; //Blank out right side
// System.out.printf("%-20.30s %-20.30s%n",formL, formR);
Out.getDisp().renderLine(formL + " " + formR); //20 Spaces
}// for (int count = 1; count <= left.size() || count <= right.size(); count++)
Out.setDisp(1); //Set to Text
}
|
9a8949a2-473a-410a-94b7-8e4952f065fb
| 3
|
public static String vectorCaddieToHTML(Vector<Caddie> rs){
if (rs.isEmpty())
return "<p class=\"plusbas\">Le caddie est vide.</p>";
String toReturn = "<TABLE BORDER='1' width=\"1000\">";
toReturn+="<CAPTION>Le caddie :</CAPTION>";
toReturn+="<TR>";
toReturn+="<TH> <i>Reservation n°</i></TH>";
toReturn+="<TH> <i>Spectacle</i> </TH><TH> <i>Date représentation</i></TH>";
toReturn+="<TH> <i> Zone </i></TH>";
toReturn+="<TH> <i>Nombre de places (Ajouter/Retirer)</i></TH>";
toReturn+="<TH> <i>Supprimer la réservation</i></TH>";
toReturn+="</TR>";
for (int i = 0; i < rs.size(); i++) {
toReturn+="<TR>";
toReturn+="<TH> "+(i+1)+"</TH>";
toReturn+="<TH>"+rs.elementAt(i).getNom()+" </TH><TH> "+rs.elementAt(i).getDate()+"</TH>";
toReturn+="<TH> "+rs.elementAt(i).getZone()+" ("+rs.elementAt(i).getNomZ()+")</TH>";
if (rs.elementAt(i).getQt() > 1)
toReturn+="<TH> <a href=\"caddie.jsp?idm="+rs.elementAt(i).getId()+"\" >(-)</a> "+rs.elementAt(i).getQt()+" <a href=\"caddie.jsp?idp="+rs.elementAt(i).getId()+"\" >(+)</a></TH>";
else
toReturn+="<TH>"+rs.elementAt(i).getQt()+" <a href=\"caddie.jsp?idp="+rs.elementAt(i).getId()+"\" >(+)</a></TH>";
toReturn+="<TH> <a href=\"caddie.jsp?idd="+rs.elementAt(i).getId()+"\" >(X)</a> </TH>";
toReturn+="</TR>";
}
return toReturn+"</TABLE><form action=\"\"><input type=\"submit\" name=\"valider\" value=\"Valider le caddie\"/></form>";
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.