method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
a15f816c-bcb3-4dbc-8ca0-4c283ecf5378
| 7 |
@Override
public void update(Observable o, Object arg) {
if (arg != null) {
if (arg.equals("drawBoard")) {
resetGUI();
menuModel.getBoardModel().generateNewBoard();
drawGameBoard();
}
else if (arg.equals("loadBoard")) {
menuModel.getBoardModel().addObserver(boardView); //when a board is loaded it loses it's observers, causing it to not update. This was a nightmare to debug.
resetGUI();
drawGameBoard();
}
else if (arg.equals("IOError")) {
JOptionPane.showMessageDialog(null, "No save file found or save file corrupt\nStarting new game instead");
resetGUI();
drawGameBoard();
}
else if (arg.equals("classError")) {
JOptionPane.showMessageDialog(null, "Serious error reading save file\nsave file may be corrupt\nStarting new game instead");
resetGUI();
drawGameBoard();
}
else if (arg.equals("scoresLoadFNFError")) {
JOptionPane.showMessageDialog(null, "Error reading in scores file\ncreating new scores file...\nstarting game");
resetGUI();
drawGameBoard();
}
else if (arg.equals("scoresSaveFNFError")) {
JOptionPane.showMessageDialog(null, "Error Saving Scores File\ncheck you have enough disk space?");
}
}
topPanel.repaint();
lPanel.repaint();
frame.repaint();
}
|
8b1fe41c-5730-451e-a0b4-5309f337e4df
| 6 |
private String getDatabaseStructureInfo() {
ResultSet schemaRs = null;
ResultSet catalogRs = null;
String nl = System.getProperty("line.separator");
StringBuffer sb = new StringBuffer(nl);
sb.append("Configured schema:").append(schema).append(nl);
sb.append("Configured catalog:").append(catalog).append(nl);
try {
schemaRs = getMetaData().getSchemas();
sb.append("Available schemas:").append(nl);
while (schemaRs.next()) {
sb.append(" ").append(schemaRs.getString("TABLE_SCHEM")).append(nl);
}
} catch (SQLException e2) {
log.warn("Couldn't get schemas", e2);
sb.append(" ?? Couldn't get schemas ??").append(nl);
} finally {
try {
schemaRs.close();
} catch (Exception ignore) {
}
}
try {
catalogRs = getMetaData().getCatalogs();
sb.append("Available catalogs:").append(nl);
while (catalogRs.next()) {
sb.append(" ").append(catalogRs.getString("TABLE_CAT")).append(nl);
}
} catch (SQLException e2) {
log.warn("Couldn't get catalogs", e2);
sb.append(" ?? Couldn't get catalogs ??").append(nl);
} finally {
try {
catalogRs.close();
} catch (Exception ignore) {
}
}
return sb.toString();
}
|
720a8dd5-6b4d-4d06-bf57-7216c5839e1b
| 9 |
public String nextToken() throws JSONException {
char c;
char q;
StringBuffer sb = new StringBuffer();
do {
c = next();
} while (Character.isWhitespace(c));
if (c == '"' || c == '\'') {
q = c;
for (;;) {
c = next();
if (c < ' ') {
throw syntaxError("Unterminated string.");
}
if (c == q) {
return sb.toString();
}
sb.append(c);
}
}
for (;;) {
if (c == 0 || Character.isWhitespace(c)) {
return sb.toString();
}
sb.append(c);
c = next();
}
}
|
1cacae44-ac16-4abb-81ae-198102117ed2
| 6 |
@Override
public void onStatusMessage(NetworkEvent event) {
if (getType() == Type.CLIENT) {
if (event.getEvent() == NetworkEvents.START_CLIENT)
setActive(true);
else if (event.getEvent() == NetworkEvents.SHUTDOWN_CLIENT)
setActive(false);
} else if (getType() == Type.SERVER) {
if (event.getEvent() == NetworkEvents.START_SERVER)
setActive(true);
else if (event.getEvent() == NetworkEvents.SHUTDOWN_SERVER)
setActive(false);
}
}
|
da06db7c-8523-40f0-ac49-13a6c4146735
| 4 |
public Character() {
_level = 1;
_generator = new NormalSpread();
_race = new Deva();
_class = new Ardent();
_classMap = new Vector<>();
BaseGenerator g = new SpecialSpread();
for (BaseClass bc : CLASSES) {
for (BaseRace br : RACES) {
int[] attributes = g.getAttributes();
int[] bonuses = br.getBonuses();
int[] ranks = bc.getRanks();
int[] preferred = bc.getPreferred();
int[] sums = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6; i++) {
sums[i] += attributes[ranks[i]] + bonuses[i];
}
float average = 0;
for (int index : preferred) {
average += sums[index];
}
average /= 3;
ClassMap cm = new ClassMap(bc, br, Math.round(average));
_classMap.add(cm);
}
}
}
|
fe5122d7-44fb-4e4a-80f3-cbb2d9b21cc0
| 8 |
private final void giveExpToCharacter(final MapleCharacter attacker, int exp, final boolean highestDamage, final int numExpSharers, final byte pty) {
if (highestDamage) {
if (eventInstance != null) {
eventInstance.monsterKilled(attacker, this);
} else {
final EventInstanceManager em = attacker.getEventInstance();
if (em != null) {
em.monsterKilled(attacker, this);
}
}
highestDamageChar = attacker;
}
if (exp > 0) {
final Integer holySymbol = attacker.getBuffedValue(MapleBuffStat.HOLY_SYMBOL);
if (holySymbol != null) {
if (numExpSharers == 1) {
exp *= 1.0 + (holySymbol.doubleValue() / 500.0);
} else {
exp *= 1.0 + (holySymbol.doubleValue() / 100.0);
}
}
if (attacker.hasDisease(MapleDisease.CURSE)) {
exp /= 2;
}
attacker.gainExp(exp, true, false, highestDamage, pty);
}
if(!getStats().isBoss()){
attacker.mobKilled();
} else {
attacker.bossKilled();
}
}
|
2b00a63a-aabb-43b8-b055-12a71672c2e8
| 1 |
public Ip parser(String ipStr){
String[] split = ipStr.split("\\.");
short[] ip = new short[split.length];
for(int i=0;i<split.length;i++){
ip[i] = Short.parseShort(split[i]);
}
return new Ip(ip);
}
|
98281264-c029-4271-901a-370f578ead98
| 2 |
private static ArrayList<Point> setPoints(int n)
{
Random r = new Random();
ArrayList<Point> points = new ArrayList<Point>();
ArrayList<Point> available = new ArrayList<Point>();
points.add(new Point(0, 0));
while (n > 0)
{
for (Point location : points)
{
add(points, available, location.x - 1, location.y); // left side
add(points, available, location.x + 1, location.y); // right side
add(points, available, location.x, location.y - 1); // top side
add(points, available, location.x, location.y + 1); // bottom side
}
int i = r.nextInt(available.size());
points.add(available.get(i));
available.remove(i);
n--;
}
points.remove(0);
return points;
}
|
6961cc1f-628d-4463-a7ed-3cae6594d129
| 3 |
@Override
public void buy(Command cmd)
{
cmd.execute();
if(Storage.getInstance().getRevenue() < 10000.0)
{
restaurant.setState(restaurant.getBadstate());
}else if(Storage.getInstance().getRevenue() >= 10000.0 && Storage.getInstance().getRevenue() < 20000.0)
{
restaurant.setState(restaurant.getNormalstate());
}
else
{
restaurant.setState(restaurant.getGoodstate());
}
}
|
e308a837-4424-40ca-a2d5-55857bbd0245
| 2 |
public String getAcceptKey() {
String key = this.getValue() + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
Base64 base64 = new Base64();
key = new String(base64.encode(md.digest(key.getBytes("UTF-8"))));
return key;
}
catch(NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException ex) {
Logger.getLogger(Handshake.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
|
5268b63c-db62-446a-8701-89bdb2c5b76d
| 9 |
public static void main(String[] args) {
//System.out.println("Pakkausalgoritmi: " + );
long aloitusAika = System.currentTimeMillis();
String algoritmi = System.getProperty("pakkausalgoritmi");
if (algoritmi == null)
algoritmi = "huffman";
if (args.length != 3) {
System.out.println("Vr mr argumentteja. Anna argumenttina operaatio (joko -pakkaa tai -pura), pakattavan tiedoston ja kohdetiedoston nimi.");
System.exit(1);
}
String operaatio = args[0];
File lahdeTiedostoNimi = new File(args[1]);
if (!lahdeTiedostoNimi.exists()) {
System.out.println("Lhdetiedostoa " + args[1] + " ei ole olemassa.");
System.exit(2);
}
File kohdeTiedostoNimi = new File(args[2]);
if (kohdeTiedostoNimi.exists()) {
System.out.println("Kohdetiedosto " + args[2] + " on jo olemassa, poistetaan..");
kohdeTiedostoNimi.delete();
}
try {
PakkausRajapinta pakkaaja;
if (operaatio.equals("-pakkaa")) {
if (algoritmi.toLowerCase().equals("lzw")) {
pakkaaja = new LZWPakkaus(lahdeTiedostoNimi, kohdeTiedostoNimi);
} else {
pakkaaja = new HuffmanPakkaus(lahdeTiedostoNimi, kohdeTiedostoNimi);
}
System.out.println("Aloitetaan tiedoston " + args[1] + " pakkaus...");
System.out.println("Kytettv pakkausalgoritmi: " + System.getProperty("pakkausalgoritmi"));
pakkaaja.pakkaaTiedosto();
} else {
if (operaatio.equals("-pura")) {
PurkuRajapinta purkaja;
if (algoritmi.toLowerCase().equals("lzw")) {
purkaja = new LZWPurku(lahdeTiedostoNimi, kohdeTiedostoNimi);
} else {
purkaja = new HuffmanPurku(lahdeTiedostoNimi, kohdeTiedostoNimi);
}
System.out.println("Aloitetaan tiedoston " + args[1] + " purku...");
System.out.println("Pakkausalgoritmi: " + System.getProperty("pakkausalgoritmi"));
purkaja.puraTiedosto();
}
}
long kesto = System.currentTimeMillis() - aloitusAika;
System.out.println("Valmis! Suoritus kesti " + kesto + " ms.");
System.out.println();
} catch (Exception e) {
e.printStackTrace();
}
}
|
e652c12e-ed89-424f-b11f-e80098b84c09
| 1 |
private static void shuffle(int[] arr)
{
for (int i = 0 ; i != arr.length ; ++i) {
int j = random.nextInt(arr.length - i) + i;
int t = arr[i];
arr[i] = arr[j];
arr[j] = t;
}
}
|
db5e74c3-df99-4274-882c-0e14cd00f8c4
| 0 |
public void doCancel(){}
|
e5651276-6429-4340-9144-9c6c803e8a29
| 1 |
public static void main(String[] args)
{
Song song = new Song(new File("Eine_Kleine_Nachtmusik.mid"));
try {
evaluate(new File("test.ff"), song);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
|
3b48328d-149e-4418-bcf5-3e5d5b87cad6
| 2 |
protected void move(){
if (target!= null && m.checkEnemy(target) == true)
{
//System.out.println(target);
turnTowards(target.getX(), target.getY());
move(speed) ;
}//IllegalActor here making it turn when its not there (DID JAMES ADDD THIS?)
else
{
active = false;
}
}
|
d5cd0f96-584f-49f7-bfc7-a5bfa6d43df9
| 1 |
private final List<String> getStringList (Object[] objList) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < objList.length; i++) {
list.add((String)objList[i]);
}
return list;
}
|
586a57a0-3115-48c3-aeaa-5db315343fbd
| 1 |
public List<String[]> getAttributes(){
List <String[]> l = new ArrayList<String[]>();
String[] s = new String[2];
if (masa != null){
s[0] = "masa"; s[1] = masa;
l.add(s);
}
s = new String[2];
s[0] = "CAT2OSMSHAPEID"; s[1] = getShapeId();
l.add(s);
return l;
}
|
9d14b701-5b11-40e7-99cb-02e9a3181b3e
| 1 |
private void handleChannelCountResponse(String response) {
String count = response.split(" ", 3)[1];
if (serverEventsListener != null)
serverEventsListener.channelCountReceived(count);
}
|
02b8c123-1bd3-4663-a50c-c8409e5004b5
| 2 |
private static boolean isDinheiro(String valor) {
final String NUMEROS = "0123456789.";
for (int i = 0; i < valor.length(); i++) {
char caracter = valor.charAt(i);
if (NUMEROS.indexOf(caracter) == -1) {
return false;
}
}
return true;
}
|
fb13f895-c9cc-4064-ac8e-830ddaa899a3
| 7 |
private void update_info(int[] bowl, int bowlId, int round,
boolean canPick,
boolean musTake) {
this.bowl = deepCopyArray( bowl );
this.bowlId = bowlId;
this.round = round;
this.canPick = canPick;
this.musTake = musTake;
// update the score and fruit count history for each bowl
if (0 == round) {
first_score[bowlId] = get_bowl_score( bowl );
first_history[bowlId] = deepCopyArray( bowl );
} else {
second_score[bowlId] = get_bowl_score( bowl );
second_history[bowlId] = deepCopyArray( bowl );
}
if (0 == bowlSize) {
for (int i=0; i<bowl.length; i++)
bowlSize += bowl[i];
expectation = 0.0;
for (int i=0; i<pref.length; i++)
expectation += pref[i] * bowlSize / 12.0;
if (maxScoreSoFar == 0) maxScoreSoFar = (int)expectation;
System.out.println("expectation g9 = " + expectation);
}
// we can update any information we want here
nfruits = nplayers * bowlSize;
if (0 == round) {
totalBowls = nplayers - getIndex();
} else {
totalBowls = getIndex() + 1;
}
if (lastRound != round ) {
bowlsRest = totalBowls;
lastRound = round;
}
bowlsRest--;
// update the observed distribution
// both the estimated initial distribution
// and the substracted distribution
accumulated_bowl_score[accumulated_bowl_number] = get_bowl_score( bowl );
//accumulated_bowl_history[accumulated_bowl_number] = deepCopyArray( bowl );
accumulated_bowl_number++;
double[] smoothed_bowl = new double[bowl.length];
smoothed_bowl = smooth_bowl(bowl);
update_estimated_initial_distribution( accumulated_bowl_number, smoothed_bowl );
update_substracted_distribution( totalBowls - bowlsRest - 1, smoothed_bowl );
update_estimated_remainging_distribution();
}
|
f25ea2a8-3da4-4c0f-8dd9-92f0a3fea08c
| 2 |
public void move()
{
Grid<Actor> gr = getGrid();
if (gr == null)
return;
Location loc = getLocation();
Location next = loc.getAdjacentLocation(getDirection());
if (gr.isValid(next))
moveTo(next);
else
removeSelfFromGrid();
Flower flower = new Flower(getColor());
flower.putSelfInGrid(gr, loc);
}
|
d5ded535-1831-4d51-86a7-6c89bd14a995
| 5 |
private String escapeString(String string)
{
if (
"and".equalsIgnoreCase(string)
|| "or".equalsIgnoreCase(string)
|| "not".equalsIgnoreCase(string)
) {
return '"' + string + '"';
}
String[] characters = { "\\", "(", ")", "\"" };
for (String s : characters) {
string = string.replace(s, '\\' + s);
}
if (string.matches(".*[\\s\\\\].*")) {
return '"' + string + '"';
}
return string;
}
|
12c396d0-ca72-45a7-876b-eb628291e007
| 2 |
public static int countLines(File cardfile) {
try {
LineNumberReader reader = new LineNumberReader(new FileReader(cardfile));
int cnt = 0;
while (reader.readLine() != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
} catch (Exception e) {
return 0;
}
}
|
816836cc-9c14-496f-b7af-d5cfd4e47c0a
| 0 |
public AlgorithmParametersType.ChallengeFormat createAlgorithmParametersTypeChallengeFormat() {
return new AlgorithmParametersType.ChallengeFormat();
}
|
95c16cfc-a087-4cf3-a3c2-9ddb91f8f309
| 2 |
public void DFSforReversedG(int nodeIndex) {
// push to stack, and mark explored;
pushToStack(nodeIndex);
nodesStatus.set(nodeIndex);
// printNodesStack();
// find next node this node has an directed edge to,that's not explored
// yet and do DFS on it, startBit to mark the index from which we
// should search for next neighbor node in the bitSet
int toNode = -1;
LinkedList<Integer> neighbors = reversedGraph.get(nodeIndex);
for (int i = 0; i < neighbors.size(); i++) {
toNode = neighbors.get(i);
if (!nodesStatus.get(toNode)) { // if neighbor has not been explored
DFSforReversedG(toNode);
}
}
// searched till last node;
popFromStack();
nodesFinishtime[nodeIndex] = curFinishTime;
curFinishTime++;
}
|
e6bb1971-bc76-4a40-b073-88431ecd1718
| 7 |
@Override
public boolean okMessage(final Environmental myHost, final CMMsg msg)
{
if(!super.okMessage(myHost,msg))
return false;
final MOB mob=msg.source();
if(((msg.amITarget(this))||(msg.tool()==this))
&&(msg.targetMinor()==CMMsg.TYP_ENTER)
&&(!CMLib.flags().isInFlight(mob))
&&(!CMLib.flags().isFalling(mob)))
{
final int chance=(int)Math.round(CMath.div(mobWeight(mob),mob.maxCarry())*(100.0-(3.0*mob.charStats().getStat(CharStats.STAT_STRENGTH))));
if(CMLib.dice().rollPercentage()<chance)
{
mob.location().show(mob,null,CMMsg.MSG_NOISYMOVEMENT,L("<S-NAME> attempt(s) to jump the crevasse, but miss(es) the far ledge!"));
mob.location().show(mob,null,CMMsg.MSG_OK_ACTION,L("<S-NAME> fall(s)!!!!"));
CMLib.combat().postDeath(null,mob,null);
return false;
}
}
return true;
}
|
9291c51b-b063-4328-8b4c-b273fe4d2d79
| 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(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(MainMenu.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(MainMenu.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 MainMenu().setVisible(true);
}
});
}
|
9f05f9fc-68d6-42a7-aaac-2ad2ed5ee99a
| 4 |
public List<Point> getAvailablePositions(Player player) {
List<Point> positions = new ArrayList<Point>();
int skippedCaseW = Engine.WIDTH/2 / Tile.SIZE;
int skippedCaseH = Engine.HEIGHT/2 / Tile.SIZE;
Point p = new Point(0,0);
Point posPlayer = new Point( (int) player.getX()/Tile.SIZE, (int) player.getY()/Tile.SIZE);
Box box = new Box(posPlayer.x - skippedCaseW, posPlayer.y - skippedCaseH, skippedCaseW * 2, skippedCaseH * 2);
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map[0].length; ++j) {
p.x = i; p.y = j;
if ( ! map[i][j].isWall() && ! Collide.AABB_point(box, p))
positions.add(new Point(i * Tile.SIZE, j * Tile.SIZE));
}
}
return positions;
}
|
1d2e153e-413b-4c8d-b58f-f64209b623da
| 1 |
@Before
public void setup () throws IOException {
String explicitFile = System.getProperty("org.newsclub.net.unix.testsocket");
if ( explicitFile != null ) {
this.socketFile = new File(explicitFile);
}
else {
this.socketFile = new File(new File(System.getProperty("java.io.tmpdir")), "junixsocket-test.sock");
}
this.server = AFUNIXServerSocket.newInstance();
this.server.bind(new AFUNIXSocketAddress(this.socketFile));
this.executor = Executors.newFixedThreadPool(2);
}
|
810702f5-9da4-45c2-8f22-5bfa48058acf
| 3 |
private void loadState(int state) {
if (state == STARTMENU) {
gameStates[state] = new StartMenu(this);
} else if (state == CHARACTERSELECT) {
gameStates[state] = new CharacterSelect(this);
} else if (state == GAME) {
gameStates[state] = new Game(this, character);
}
}
|
1ddfb288-dff7-4b0e-a229-1185d4979fdc
| 9 |
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SimpleEmailAddress other = (SimpleEmailAddress) obj;
if (email == null) {
if (other.email != null)
return false;
} else if (!email.equals(other.email))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
|
39b6c74e-5c67-44fe-96d6-3d7d416844f0
| 6 |
private boolean safe(Room room) {
if(!wumpusKB.known(room) || wumpusKB.evaluate(room)) { return false; }
if(!batKB.known(room) || batKB.evaluate(room) ) { return false; }
if(!pitKB.known(room) || pitKB.evaluate(room) ) { return false; }
return true;
}
|
03048fbf-9f9e-4bed-b2f1-6b8a7a3ab365
| 0 |
public static condition condFromString(String name) {
return getEnumFromString(condition.class, name);
}
|
214c1998-163c-40a7-b412-5aa15af78d00
| 9 |
public void updateAutoSize(CellView view) {
if (view != null && !isEditing()) {
Rectangle2D bounds = (view.getAttributes() != null) ? GraphConstants
.getBounds(view.getAttributes())
: null;
AttributeMap attrs = getModel().getAttributes(view.getCell());
if (bounds == null)
bounds = GraphConstants.getBounds(attrs);
if (bounds != null) {
boolean autosize = GraphConstants.isAutoSize(view
.getAllAttributes());
boolean resize = GraphConstants.isResize(view
.getAllAttributes());
if (autosize || resize) {
Dimension2D d = getUI().getPreferredSize(this, view);
bounds.setFrame(bounds.getX(), bounds.getY(), d.getWidth(),
d.getHeight());
// Remove resize attribute
snap(bounds);
if (resize) {
if (view.getAttributes() != null)
view.getAttributes().remove(GraphConstants.RESIZE);
attrs.remove(GraphConstants.RESIZE);
}
view.refresh(getGraphLayoutCache(), getGraphLayoutCache(), false);
}
}
}
}
|
0d1a668b-c3a9-45f1-a6b7-403b287636bc
| 2 |
public static void main(String[] args) {
int i; // 循环计数变量
int Index = a.length;// 数据索引变量
System.out.print("排序前: ");
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s ", a[i]);
System.out.println("");
ShellSort(Index - 1); // 选择排序
// 排序后结果
System.out.print("排序后: ");
for (i = 0; i < Index - 1; i++)
System.out.printf("%3s ", a[i]);
System.out.println("");
}
|
6fcf7ae3-efe0-4c5d-9231-729764a815e7
| 1 |
public void mute() {
if(masterVolume == 0f)
masterVolume = 2f;
else
masterVolume = 0f;
adjustVolume = true;
}
|
c1f2559d-552b-4241-b266-0bc792eb71d6
| 1 |
public static void init(final String initCode) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MainWindow window = new MainWindow(initCode);
window.frmCompreterA.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
|
c852241e-328f-4fd5-b0ff-e7dc3f2e4a26
| 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;
}
|
2741eff5-00d0-4b4a-a8df-f3e19fedc514
| 2 |
private double rowAdd(Double[][] mat, int rowTo, int rowFrom, double scaleFactor)
{
if (rowTo == rowFrom)
return rowScale(mat, rowTo, scaleFactor + 1);
for (int i = 0; i < mat[0].length; i++)
{
mat[rowTo][i] = mat[rowTo][i] + mat[rowFrom][i] * scaleFactor + 0.0;
}
return 1.0;
}
|
d30d696a-b504-4e76-a472-c9dd9df06b87
| 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(GuessingGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(GuessingGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(GuessingGame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(GuessingGame.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 GuessingGame().setVisible(true);
}
});
}
|
f4227356-f271-4177-a117-a9b19abfb5ea
| 5 |
public void execute(Nodo inicio)
{
fila.add(inicio);
distancias[inicio.getId()]=0;
pred[inicio.getId()]=inicio.getId();
for(Link a: inicio.getLinks()){
distancias[a.getDestino().getId()]=a.getPeso();
pred[a.getDestino().getId()]= inicio.getId();
}
while(!fila.isEmpty())
{
Nodo work= nexter();
for (Link a:work.getLinks())
{
Nodo dest=a.getDestino();
int peso = a.getPeso();
int dist= distancias[work.getId()] + peso;
if( !(done.contains(dest))) fila.add(dest);
if(dist < distancias[dest.getId()] )
{
distancias[dest.getId()]= dist;
pred[dest.getId()]= work.getId();
}
}
fila.remove(work);
done.add(work);
}
}
|
457d3d20-2446-4195-81d0-5fa03d9621de
| 7 |
public static Vector<String> findPackages() {
Vector<String> result;
StringTokenizer tok;
String part;
File file;
JarFile jar;
JarEntry entry;
Enumeration<JarEntry> enm;
HashSet<String> set;
result = new Vector<String>();
set = new HashSet<String>();
// check all parts of the classpath, to include additional classes from
// "parallel" directories/jars, not just the first occurence
tok = new StringTokenizer(
System.getProperty("java.class.path"),
System.getProperty("path.separator"));
while (tok.hasMoreTokens()) {
part = tok.nextToken();
if (VERBOSE)
System.out.println("Classpath-part: " + part);
// find classes
file = new File(part);
if (file.isDirectory()) {
set = getSubDirectories(null, file, set);
}
else if (file.exists()) {
try {
jar = new JarFile(part);
enm = jar.entries();
while (enm.hasMoreElements()) {
entry = (JarEntry) enm.nextElement();
// only directories
if (entry.isDirectory())
set.add(entry.getName().replaceAll("/", ".").replaceAll("\\.$", ""));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
// sort result
set.remove("META-INF");
result.addAll(set);
Collections.sort(result, new StringCompare());
return result;
}
|
4091c186-0e57-4a94-acb6-0e5227b82868
| 0 |
public Combinacion(int idCombinacion, int claveles, int margaritas, int gladiolos, int rosas, int gerberas, int verdes, int lilium, int alstromeria, int anturium, int lisiantus, int paniculata, int ruscus) {
this.idCombinacion = idCombinacion;
this.claveles = claveles;
this.margaritas = margaritas;
this.gladiolos = gladiolos;
this.rosas = rosas;
this.gerberas = gerberas;
this.verdes = verdes;
this.lilium = lilium;
this.alstromeria = alstromeria;
this.anturium = anturium;
this.lisiantus = lisiantus;
this.paniculata = paniculata;
this.ruscus = ruscus;
}
|
f863a547-69c5-4d54-8151-376152501578
| 3 |
private List<IdentityDisc> getIdentityDiscsOfGrid(Grid grid) {
final List<IdentityDisc> identityDiscs = new ArrayList<IdentityDisc>();
for (Element e : grid.getElementsOnGrid())
if (e instanceof IdentityDisc && !(e instanceof ChargedIdentityDisc))
identityDiscs.add((IdentityDisc) e);
return identityDiscs;
}
|
79492a72-0e7a-47d3-af8e-f47887a1f73b
| 7 |
public Boolean cadastarNovo(Cidadao cidadao) {
Boolean sucesso = false;
Connection connection = conexao.getConnection();
try {
String valorDoComandoUm = comandos.get("cadastarNovo" + 1);
String valorDoComandoDois = comandos.get("cadastarNovo" + 2);
StringBuilder query = new StringBuilder(valorDoComandoUm);
for (int i = 0; i < cidadao.getTelefones().size() + cidadao.getCelulares().size(); i++) {
query.append("\n").append(valorDoComandoDois);
}
connection.setAutoCommit(false);
PreparedStatement preparedStatement = connection.prepareStatement(query.toString());
query.delete(0, query.length());
int indice = 1;
setString(indice++, cidadao.getNomeCompleto(), preparedStatement);
setString(indice++, cidadao.getLogradouro(), preparedStatement);
setInt(indice++, cidadao.getNumeroImovel(), preparedStatement);
setInt(indice++, cidadao.getBairro().getCodigo(), preparedStatement);
setString(indice++, cidadao.getBairro().getNome(), preparedStatement);
setInt(indice++, cidadao.getBairro().getCidade().getCodigo(), preparedStatement);
setString(indice++, cidadao.getBairro().getCidade().getNome(), preparedStatement);
setInt(indice++, cidadao.getBairro().getCidade().getEstado().getCodigo(), preparedStatement);
for (Telefone telefone : cidadao.getTelefones()) {
setInt(indice++, telefone.getDDD().getNumero(), preparedStatement);
setString(indice++, telefone.getNumero(), preparedStatement);
setString(indice++, "Tel", preparedStatement);
}
for (Celular celular : cidadao.getCelulares()) {
setInt(indice++, celular.getDDD().getNumero(), preparedStatement);
setString(indice++, celular.getNumero(), preparedStatement);
setString(indice++, "Cel", preparedStatement);
}
preparedStatement.execute();
connection.commit();
connection.setAutoCommit(true);
sucesso = true;
} catch (SQLException ex) {
try {
connection.rollback();
} catch (SQLException ex1) {
}
throw new RuntimeException(ex.getMessage());
} catch (NullPointerException ex) {
throw new RuntimeException(ex.getMessage());
} catch (Exception ex) {
throw new RuntimeException(ex.getMessage());
} finally {
conexao.fecharConnection();
}
return sucesso;
}
|
99a893c2-f336-4264-afc3-a56db57f81b7
| 0 |
private void initialize(){
frame.setIconImage(MAIN_ICON.getImage());
frame.setSize(WINDOW_SIZE);
frame.setResizable(false);
frame.setLocation((int) (SCREEN_SIZE.getWidth() / 2 - frame.getWidth() / 2),
(int) (SCREEN_SIZE.getHeight() / 2 - frame.getHeight() / 2));
frame.setDefaultCloseOperation(frame.DISPOSE_ON_CLOSE);
frame.setLayout(new BorderLayout());
frame.add(new JPanel(), BorderLayout.NORTH);
frame.add(new JPanel(), BorderLayout.EAST);
frame.add(new JPanel(), BorderLayout.WEST);
frame.add(new JPanel(), BorderLayout.SOUTH);
JPanel contentPanel = new JPanel();
contentPanel.setLayout(new BoxLayout(contentPanel, BoxLayout.Y_AXIS));
contentPanel.add(placeTextFields());
contentPanel.add(placeButtons());
frame.add(contentPanel, BorderLayout.CENTER);
}
|
550bb6be-560c-4ce7-9e57-b8fb6149439f
| 7 |
private final void diff(final Git session, final RevWalk walk,
final RevCommit commitNew, final ObjectReader reader)
throws MissingObjectException, IncorrectObjectTypeException,
IOException {
int i = 0;
if (commitNew.getParentCount() == 0) {
final RevTree treeNew = commitNew.getTree();
this.treeParserNew.reset(reader, treeNew.getId());
final int time = commitNew.getCommitTime();
try {
final List<DiffEntry> diffs = session.diff()
.setOldTree(new EmptyTreeIterator())
.setNewTree(this.treeParserNew)
.setShowNameAndStatusOnly(true).call();
final Iterator<DiffEntry> diffsIterator = diffs.iterator();
while (diffsIterator.hasNext()) {
this.changed.put(diffsIterator.next().getNewPath(), time);
}
} catch (final GitAPIException e) {
this.io.handleException(ExceptionHandle.CONTINUE, e);
}
} else {
while (i < commitNew.getParentCount()) {
final RevCommit commitOld = commitNew.getParent(i++);
if (this.visited.add(commitOld.getName())) {
final RevTree treeOld = walk.parseTree(commitOld);
final RevTree treeNew = commitNew.getTree();
diff(session, walk, commitOld, reader);
this.treeParserNew.reset(reader, treeNew.getId());
this.treeParserOld.reset(reader, treeOld.getId());
final int time = commitNew.getCommitTime();
try {
final List<DiffEntry> diffs = session.diff()
.setOldTree(this.treeParserOld)
.setNewTree(this.treeParserNew)
.setShowNameAndStatusOnly(true).call();
final Iterator<DiffEntry> diffsIterator = diffs
.iterator();
while (diffsIterator.hasNext()) {
this.changed.put(diffsIterator.next().getNewPath(),
time);
}
} catch (final GitAPIException e) {
this.io.handleException(ExceptionHandle.CONTINUE, e);
}
}
}
}
}
|
52c1481a-a418-448f-9b08-1236da237240
| 2 |
public void RunTest() throws Exception {
System.out.println("RunTest.");
Long id = (Long)conn.call(new CommandContent().addMethod("getClientId"));
System.out.println("Client connection id " + id);
System.out.println("Start calls.");
for (int i = 0; i < callcount; i++) {
String ans = (String)conn.call("Echo(?)", "SYNC CALL");
System.out.println(" Answer from server: " + ans);
}
System.out.println("Finish calls.");
System.out.println("Start sends.");
for (int i = 0; i < callcount; i++) {
conn.send(new CommandContent().addMethod("Echo", new CommandParams("ASYNC CALL")));
}
System.out.println("Finish sends.");
}
|
5e482f43-861a-4817-8b12-59e75c591ec5
| 4 |
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession()
: null;
threadLocal.set(session);
}
return session;
}
|
6b46b24d-4f7a-4e0f-b8bb-cd6769fcf053
| 2 |
@Override
public void dealDamage(int amount, Object source) {
if (source instanceof Projectile) {
Projectile p = (Projectile) source;
if (p.getImageName().equals("arrow")) return;
}
super.dealDamage(amount, source);
}
|
0390a3a4-5cc8-49e9-81ed-740d50df75e3
| 8 |
public void printMovieInfo(Movie movie) {
int index = 0;
_showTimes = new ArrayList<ShowTime>();
System.out.println();
System.out.println(movie.getTitle());
System.out.println("=================================");
System.out.println("AVAILABLE IN\t: " + movie.getType());
System.out.println("CAST\t\t: " + movie.getCast());
System.out.println("DIRECTOR\t: " + movie.getDirector());
System.out.println("LANGUAGE\t: " + movie.getLanguage());
System.out.println("OPENING\t\t: " + movie.getOpening());
System.out.println("RUNTIME\t\t: " + movie.getRunTime());
System.out.println("RATING\t\t: " + movie.getRating());
System.out.println("Description\t: " + movie.getDetails());
// Printing movie showtimes
System.out.println();
System.out.println("SHOWTIMES");
System.out.println("=========");
for(Cineplex cineplex: cineplexBL.getCineplexes()) {
List<Cinema> cinemas = cineplex.getCinemas(movie);
if(cinemas == null) {
continue;
}
System.out.println(cineplex.getCineplexName());
System.out.println("..................................");
// Go through every cinemas
for(Cinema cinema: cinemas) {
List<ShowTime> showTimes = cinema.getShowTimes(movie);
if(showTimes == null) {
continue;
}
Hashtable<String, List<ShowTime>> showTimeHashTable = new Hashtable<String, List<ShowTime>>();
//Preprocessing for showTime to follow the cathay format
SimpleDateFormat sdf = new SimpleDateFormat("d MMM, E");
for(ShowTime st: showTimes) {
String d = sdf.format(st.getTime());
if(showTimeHashTable.get(d) == null) {
showTimeHashTable.put(d, new ArrayList<ShowTime>());
}
showTimeHashTable.get(d).add(st);
}
SimpleDateFormat timeformat = new SimpleDateFormat("HH:mm");
for(Enumeration<String> e = showTimeHashTable.keys();e.hasMoreElements();) {
String dateString = e.nextElement();
System.out.print(dateString);
for(ShowTime showTime: showTimeHashTable.get(dateString)) {
// showTime can be accessed using the index. It is in the sequence it is printed.
// index starts at zero even though the index printed out start at 1. -1 before accessing.
_showTimes.add(showTime);
String time = new SimpleDateFormat("HH:mm").format(showTime.getTime());
System.out.print("\t[" + (index+1) + "] " + time);
index++;
}
System.out.println();
}
System.out.println();
}
}
}
|
4d72495b-e3fc-4379-aba6-a3e26a1bda37
| 6 |
public Ticket retrieveTicket(int id) {
Ticket result = null;
ResultSet rs = null;
PreparedStatement statement = null;
try {
statement = conn.prepareStatement("select * from Tickets where TicketID = ?");
statement.setInt(1, id);
int workerid_fk;
int ticketid;
String subject;
boolean pending;
boolean active;
boolean closed;
rs = statement.executeQuery();
if (rs.next()) {
workerid_fk = rs.getInt("WorkerID_FK");
ticketid = rs.getInt("TicketID");
subject = rs.getString("Subject");
pending = rs.getBoolean("Pending");
active = rs.getBoolean("active");
closed = rs.getBoolean("closed");
result = ModelFactory.createTicket(ticketid, workerid_fk, subject, pending, active, closed);
} else {
}
} catch(SQLException e){
e.printStackTrace();
} finally {
try { if (rs != null) rs.close(); } catch (Exception e) {}
try { if (statement != null) statement.close(); } catch (Exception e) {}
}
return result;
}
|
d90ec9e4-3b7f-4d4f-98fd-41adc632d77a
| 1 |
public void calculateWeights(){
for(int i = 0; i < itemIds.length; i++){
weightsUserId1[i] = pearson * ratings1[i];
weightsUserId2[i] = pearson * ratings2[i];
}
}
|
6f2e89a1-2df6-4bab-9225-632a1f097d83
| 9 |
private boolean fn_arr_member() {
// check format: "(" [ argument_list ] ")" | "[" expression "]"
if (lexicalAnalyzer.getToken().getType().equals(LexicalAnalyzer.tokenTypesEnum.PAREN_OPEN.name())) {
//check format: "(" [ argument_list ] ")"
if (!operatorPush(new Opr_SAR(lexicalAnalyzer.getToken()))) {
return false;
}
BALPush(new BAL_SAR());
lexicalAnalyzer.nextToken();
if (lexicalAnalyzer.getToken().getType().equals(LexicalAnalyzer.tokenTypesEnum.PAREN_CLOSE.name())) {
if (!closingParen()) {
return false;
}
EALPush();
functionPush();
lexicalAnalyzer.nextToken();
return true;
}
if (!argument_list()) {
return false;
}
if (!closingParen()) {
return false;
}
EALPush();
functionPush();
lexicalAnalyzer.nextToken();
return true;
} else if (lexicalAnalyzer.getToken().getType().equals(LexicalAnalyzer.tokenTypesEnum.ARRAY_BEGIN.name())) {
//check format: "[" expression "]"
if (!operatorPush(new Opr_SAR(lexicalAnalyzer.getToken()))) {
return false;
}
lexicalAnalyzer.nextToken();
if (!expression()) {
return false;
}
//check for array end
lexicalAnalyzer.nextToken();
arrayClose();
return ArrayRefPush();
}
return false;
}
|
3f8ca680-fa2b-44bd-b983-246b0d531ddb
| 6 |
public synchronized boolean split(Bucket bucket)
{
boolean containsLocalNode = bucket.containsBucketContact(getLocalNode().getNodeId());
if ((containsLocalNode || bucket.equals(smallestSubtreeBucket)) && !bucket.isTooDeep())
{
List<Bucket> buckets = bucket.split();
Bucket left = buckets.get(0);
Bucket right = buckets.get(1);
if (containsLocalNode)
{
if (left.containsBucketContact(getLocalNode().getNodeId()))
smallestSubtreeBucket = right;
else if (right.containsBucketContact(getLocalNode().getNodeId()))
smallestSubtreeBucket = left;
else
throw new IllegalStateException("Neither left nor right Bucket contains the local Node");
}
// The left one replaces the current bucket in the Trie!
bucketTrie.put(left.getBucketId(), left);
bucketTrie.put(right.getBucketId(), right);
//the bucket is split
return true;
}
return false;
}
|
9f0521be-51e3-4fb6-93d7-e1921fb8519f
| 2 |
public void weeklyBonus(Player player)
{
if (color == player.getColor()) {
for(CastleBuilding b: buildings) {
b.weeklyBonus(player, this);
}
}
}
|
d9ca7609-3231-4754-aa6b-3a6816636532
| 4 |
public static void main(String[] args) {
GameKeitai1 taro = new GameKeitai1(
"太郎", "012-1234-5678", "taro@test.jp");
GameKeitai2 hanako = new GameKeitai2(
"花子", "999-8888-7777", "hanako@test.jp");
for(int i=0; i<3; i++){
taro.denwaSuru();
}
for(int i=0; i<3; i++){
hanako.denwaSuru();
}
taro.mail();
taro.mail("送信");
taro.mail("送信", 2);
hanako.mail();
hanako.mail("受信");
hanako.mail("受信", 2);
for(int i=0; i<3; i++){
taro.gemeSuru();
}
for(int i=0; i<3; i++){
hanako.gemeSuru();
}
System.out.print("インスタンスtaroの情報: ");
printField(taro);
System.out.print("インスタンスhanakoの情報: ");
printField(hanako);
}
|
9ef93061-663e-41bf-9742-861b9484fead
| 5 |
public void Commands_time() {
if(args.length == 1) {
if(args[0].equalsIgnoreCase("day")) {
player.getWorld().setTime(0);
}
else if(args[0].equalsIgnoreCase("night")) {
player.getWorld().setTime(12000);
}
else {
player.sendMessage(ChatColor.RED + "Argument invialide");
}
}
else if(args.length == 2 && args[0].equalsIgnoreCase("set")) {
int time = Integer.parseInt(args[1]);
player.getWorld().setTime(time);
}
else {
player.sendMessage(ChatColor.RED + "Veuillez respecter la syntaxe de la commande.");
}
}
|
69bf5970-e0df-4b1d-b4fb-267ccccb1993
| 8 |
public void initAStar() {
if (startX<0||startX>=width||endX<0||endX>=width
||startY<0||startY>=height||endY<0||endY>=height) {
log("ERROR: invalid initialization values!");
}
setHeuristicAll();
openqueue.clear();
grid[startY][startX].G = 0.0;
grid[startY][startX].calcF();
grid[startY][startX].parent = null;
openqueue.add(grid[startY][startX]);
}
|
f249af31-ba7c-40cd-86c0-f0ee15eadd10
| 6 |
@Override
public ExplicitMod deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
for (String s : Constants.ESCAPED_MODS) {
Pattern p = Pattern.compile(s);
Matcher m = p.matcher(jsonElement.getAsString());
while (m.find()) {
if (m.groupCount() == 1) {
if (jsonElement.getAsString().contains("%")) {
return new ExplicitMod(new PercentageProperty(jsonElement.getAsString(), 1, AugmentColour.DEFAULT_AUGMENT, Integer.parseInt(m.group(1))));
} else if (jsonElement.getAsString().contains(".")) {
return new ExplicitMod(new DecProperty(jsonElement.getAsString(), 1, AugmentColour.DEFAULT_AUGMENT, Double.parseDouble(m.group(1))));
} else {
return new ExplicitMod(new IntProperty(jsonElement.getAsString(), 1, AugmentColour.DEFAULT_AUGMENT, Integer.parseInt(m.group(1))));
}
} else if (m.groupCount() == 2) {
return new ExplicitMod(new MinMaxProperty(jsonElement.getAsString(), 1, AugmentColour.DEFAULT_AUGMENT, Integer.parseInt(m.group(1)), Integer.parseInt(m.group(2))));
}
}
}
return null;
}
|
aeff30e3-bd7b-4064-94d7-9244ece1514f
| 8 |
public LinkedList<Moneys> take(int am,String player,String game)
{
if(this==printer.pot && score < am)//the pot will always give itself money out of air rather than go negative
{
LinkedList<Moneys> temp=new LinkedList<Moneys>();
temp.add(new Moneys(this.name,am-score));
this.give(temp,game);
}
LinkedList<Moneys> ret=new LinkedList<Moneys>();
score-=am;
int amount=am;
while(amount > 0)
{
if(!money.isEmpty())
{
Moneys take=money.getLast();
for(Moneys m : money)
if(m.owner.equals(player))
take=m;
if(take.amount > amount)
{
ret.add(new Moneys(take.owner,amount));
take.amount-=amount;
amount=0;
}
else
{
ret.add(take);
money.remove(take);
amount-=take.amount;
}
}
else
{
ret.addAll(printer.pot.take(amount, player,game));
amount =0;
}
}
if(in)
writestack();
return ret;
}
|
fe4f536f-710e-4597-88de-ba7ee73a369a
| 4 |
public void deleteBookLanguage(long id) {
Connection con = null;
Statement stmt = null;
try {
DBconnection dbCon = new DBconnection();
Class.forName(dbCon.getJDBC_DRIVER());
con = DriverManager.getConnection(dbCon.getDATABASE_URL(),
dbCon.getDB_USERNAME(), dbCon.getDB_PASSWORD());
stmt = con.createStatement();
stmt.execute("Delete From bookLanguage Where lan_id = " + String.valueOf(id));
} catch (SQLException | ClassNotFoundException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
} finally {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
System.err.println("Caught Exception: " + ex.getMessage());
}
}
}
|
47149457-6d83-4c28-a798-bd7397de0eea
| 1 |
@Override
public void removeClickListener(ClickListener listener) {
if (listener != null) this.clickListeners.remove(listener);
}
|
a5625ff5-c7cc-4f77-ac67-364bf2c1ccf8
| 7 |
public String toString() {
String s = "lastCheckpoint : int = " + String.valueOf(this.lastCheckPoint) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
s = s + "identifierStack : char["+(this.identifierPtr + 1)+"][] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.identifierPtr; i++) {
s = s + "\"" + String.valueOf(this.identifierStack[i]) + "\","; //$NON-NLS-1$ //$NON-NLS-2$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "identifierLengthStack : int["+(this.identifierLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.identifierLengthPtr; i++) {
s = s + this.identifierLengthStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "astLengthStack : int["+(this.astLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.astLengthPtr; i++) {
s = s + this.astLengthStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "astPtr : int = " + String.valueOf(this.astPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
s = s + "intStack : int["+(this.intPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.intPtr; i++) {
s = s + this.intStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "intPtr : int = " + String.valueOf(this.intPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
s = s + "expressionLengthStack : int["+(this.expressionLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.expressionLengthPtr; i++) {
s = s + this.expressionLengthStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "expressionPtr : int = " + String.valueOf(this.expressionPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
s = s + "genericsIdentifiersLengthStack : int["+(this.genericsIdentifiersLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.genericsIdentifiersLengthPtr; i++) {
s = s + this.genericsIdentifiersLengthStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "genericsLengthStack : int["+(this.genericsLengthPtr + 1)+"] = {"; //$NON-NLS-1$ //$NON-NLS-2$
for (int i = 0; i <= this.genericsLengthPtr; i++) {
s = s + this.genericsLengthStack[i] + ","; //$NON-NLS-1$
}
s = s + "}\n"; //$NON-NLS-1$
s = s + "genericsPtr : int = " + String.valueOf(this.genericsPtr) + "\n"; //$NON-NLS-1$ //$NON-NLS-2$
s = s + "\n\n\n----------------Scanner--------------\n" + this.scanner.toString(); //$NON-NLS-1$
return s;
}
|
c8d8ff2a-4f30-46c4-b222-fa26653eef9b
| 7 |
public static void main (String [] args) throws Exception {
try {
System.out.println(System.getProperty("user.dir"));
CatalogReader foo = new CatalogReader ("Catalog.xml");
Map <String, CountedTableData> res = foo.getCatalog ();
System.out.println (foo.printCatalog (res));
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
System.out.format ("\nSQL>");
String soFar = in.readLine () + " ";
// loop forever, or until someone asks to quit
while (true) {
// keep on reading from standard in until we hit a ";"
while (soFar.indexOf (';') == -1) {
soFar += (in.readLine () + " ");
}
// split the string
String toParse = soFar.substring (0, soFar.indexOf (';') + 1);
soFar = soFar.substring (soFar.indexOf (';') + 1, soFar.length ());
toParse = toParse.toLowerCase ();
// parse it
ANTLRStringStream parserIn = new ANTLRStringStream (toParse);
SQLLexer lexer = new SQLLexer (parserIn);
CommonTokenStream tokens = new CommonTokenStream(lexer);
SQLParser parser = new SQLParser (tokens);
// if we got a quit
if (parser.parse () == false) {
break;
}
// print the results
System.out.println ("RESULT OF PARSING");
System.out.println ("Expressions in SELECT:");
ArrayList <Expression> mySelect = parser.getSELECT ();
for (Expression e : mySelect)
System.out.println ("\t" + e.print ());
System.out.println ("Tables in FROM:");
Map <String, String> myFrom = parser.getFROM ();
System.out.println ("\t" + myFrom);
System.out.println ("WHERE clause:");
Expression where = parser.getWHERE ();
if (where != null)
System.out.println ("\t" + where.print ());
System.out.println ("GROUPING att:");
String att = parser.getGROUPBY ();
if (att != null)
System.out.println ("\t" + att);
Checker checker=new Checker(res,mySelect, myFrom, where,att);
checker.check();
//Runner.run();
//Worker worker=new Worker(res,mySelect,myFrom,where,att);
Analyzer analyzer=new Analyzer(res,mySelect,myFrom,where,att);
long startTime = System.currentTimeMillis();
analyzer.analyze();
long endTime = System.currentTimeMillis();
System.out.println("The run took " + (endTime - startTime) + " milliseconds");
System.out.format ("\nSQL>");
}
} catch (Exception e) {
System.out.println("Error! Exception: " + e.getStackTrace());
}
}
|
20913143-afe1-4465-9241-d0c97240f862
| 0 |
void setAsPossibleBreakPoint() {
possibleBreakpoint = true;
}
|
bcbaf167-c719-4d71-820c-ca34707ce998
| 2 |
public static void destroySession(int sessionId) {
Actions.addAction(new Action(ActionType.INFO, "Attempting to kick session id: 0x" + Integer.toHexString(sessionId) + " from the Server..."));
Session sess = sessions.get(sessionId);
if(sess != null) {
final Channel c = sess.getChannel();
BroadcastMessage kickMsg = new BroadcastMessage(-1, "SERVER", sess.getUser().getUsername() +
" has been kicked by the Server.");
NetworkMultipleEvent broadcastEvent = Events.createNewEvent((Server.getChannelGroup()));
broadcastEvent.setMessage(kickMsg);
Sessions.removeSession(sessionId);
broadcastEvent.setFutureListener(new ChannelGroupFutureListener() {
@Override
public void operationComplete(ChannelGroupFuture future) throws Exception {
if(c != null) {
c.disconnect();
}
}
});
broadcastEvent.send();
}
}
|
7633f956-aa0d-469a-99cc-326d2abbf2b8
| 0 |
public void setLength(long value) {
this.length = value;
}
|
ef635bef-48b2-45c0-bb87-ed0f99890333
| 2 |
public BeansContainer() {
registry = new HashMap<Class<?>, Class<?>>();
interceptors = new Interceptor[] {
new TransactionableInterceptor(),
new BeanInterceptor()
};
}
|
f844ba2b-3626-4460-8ca0-c0c47342a1d8
| 0 |
public AssetManager getAssetManager(){
return assetManager;
}
|
20f24890-77f3-4830-8767-fad8c3ccd5cd
| 4 |
public GLWindow() throws InterruptedException {
try {
Display.setDisplayMode(new DisplayMode(800, 600));
Display.setTitle("Renderer");
Display.setResizable(false);
Display.create();
} catch (LWJGLException e) { // Fix for old Computers | Nvidia Processors
if(e.getMessage() == "Pixel Format Not Accelerated"){
System.setProperty("Dorg.lwjgl.opengl.Display.allowSoftwareOpenGL", "true");
Display.setTitle(Display.getTitle() + " -missing latest Gcard drivers (Running in safe mode)");
try {
Display.create();
} catch (LWJGLException e1) {
System.out.print("Error Occured, OpenGL SoftwareMode failed, Could not Create Display");
e1.printStackTrace();
}
}
}
initVar();
initGL();
while(!Display.isCloseRequested()){
glPushMatrix();
Update();
GLRender();
glPopMatrix();
Display.update();
upDatevecs();
Thread.sleep(1000/60);
}
Display.destroy();
System.exit(0);
}
|
3c87f70d-e11a-4157-931d-b6aacbbed084
| 3 |
public void createWindow() throws Exception {
Display.setFullscreen(false);
this.theWorld.generate();
/*
* DisplayMode d[] = Display.getAvailableDisplayModes(); for (int i = 0;
* i < d.length; i++) { if (d[i].getWidth() == 640 && d[i].getHeight()
* == 480 && d[i].getBitsPerPixel() == 32) { displayMode = d[i]; break;
* } }
*/
Display.setDisplayMode(new DisplayMode(displaywidth, displayheight));
Display.setTitle("CliffieGame");
Display.create();
if (this.skyColor == 0) {
this.skyColor = 10079487;
}
if (this.fogColor == 0) {
this.fogColor = 16777215;
}
if (this.cloudColor == 0) {
this.cloudColor = 16777215;
}
fogr = (float) (fogColor >> 16 & 255) / 255.0F;
fogg = (float) (fogColor >> 8 & 255) / 255.0F;
fogb = (float) (fogColor & 255) / 255.0F;
skyr = (float) (skyColor >> 16 & 255) / 255.0F;
skyg = (float) (skyColor >> 8 & 255) / 255.0F;
skyb = (float) (skyColor & 255) / 255.0F;
//System.out.println("Rs: " + fogr + " " + skyr);
//System.out.println("Gs: " + fogg + " " + skyg);
//System.out.println("Bs: " + fogb + " " + skyb);
}
|
5397d80a-cf37-4093-9625-6410fac3faf3
| 5 |
public CheckResultMessage check4(int day) {
BigDecimal a1 = new BigDecimal(0);
int r3 = get(13, 5);
int c3 = get(14, 5);
if (version.equals("2003")) {
try {
in = new FileInputStream(file);
hWorkbook = new HSSFWorkbook(in);
a1 = getValue(r3 + day, c3 + 1, 3).subtract(
getValue(r3 + day, c3, 3));
if (0 != getValue(r3 + day, c3 + 2, 3).compareTo(a1)) {
return error("支付机构汇总报表<" + fileName + ">客户账户内部转账手续费收入:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
in = new FileInputStream(file);
xWorkbook = new XSSFWorkbook(in);
a1 = getValue1(r3 + day, c3 + 1, 3).add(
getValue1(r3 + day, c3 + 2, 3));
if (0 != getValue1(r3 + day, c3 + 2, 3).compareTo(a1)) {
return error("支付机构汇总报表<" + fileName + ">客户账户内部转账手续费收入:"
+ day + "日错误");
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pass("支付机构汇总报表<" + fileName + ">客户账户内部转账手续费收入:" + day + "日正确");
}
|
c7448f71-4af4-49d8-b2ef-47473392a029
| 8 |
public static int[] quickSort(int[] array, int start, int end) {
int s = start;
int e = end;
if(end-start < 1) {
return array;
}
if(end-start == 1) {
if(array[start] > array[end]) {
int tmp = array[start];
array[start] = array[end];
array[end] = tmp;
}
return array;
}
int key = array[start];
while(start < end) {
while(array[end] > key) {
end--;
}
if(end <= start) {
break;
} else {
int tmp = array[start];
array[start] = array[end];
array[end] = tmp;
}
while(array[start] < key) {
start++;
}
if(end <= start) {
break;
} else {
int tmp = array[start];
array[start] = array[end];
array[end] = tmp;
}
}
array = quickSort(array, s, end);
array = quickSort(array, end+1, e);
return array;
}
|
53d8797a-2d24-456c-b124-bbcd85ded8ed
| 1 |
public static void main(String[] args) {
ConcreteAggregate aggregate = new ConcreteAggregate();
aggregate.addObject("1");
aggregate.addObject("3");
aggregate.addObject("5");
aggregate.addObject("7");
aggregate.addObject("9");
Iterator iterator = new ConcreteIterator(aggregate);
Object object = iterator.first();
System.out.println("first state = " + object);
while (iterator.hasNext()) {
System.out.println("current state = " + iterator.current());
iterator.next();
}
}
|
e2f08d21-ee15-4de6-a322-a03ff1f2dc2d
| 6 |
public ListNode deleteDuplicates(ListNode head) {
// Start typing your Java solution below
// DO NOT write main() function
if (head == null || head.next == null)
return head;
ListNode prev = new ListNode(0); // 当前的前驱节点
ListNode root = prev; // 整体的前驱节点
int preVal = head.val;
ListNode cur = head;
boolean dup = false;
while (cur.next != null) {
if (cur.next.val == preVal) {
dup = true;
} else {
if (!dup) { // 不重复的话就把前驱结点移到当前节点,否则忽略
prev.next = cur;
prev = prev.next;
}
preVal = cur.next.val;
dup = false;
}
cur = cur.next;
}
prev.next = dup ? null : cur; // 处理最后一个节点
return root.next;
}
|
9d194506-1c72-4589-bbf8-abc2201b611a
| 1 |
@Override
public final String toString()
{
return "Bencoding Exception:\n"+(this.message == null ? "" : this.message);
}
|
db4d9319-ff88-4a77-b342-c186aa8f9f26
| 6 |
GenericGFPoly(GenericGF field, int[] coefficients) {
if (coefficients.length == 0) {
throw new IllegalArgumentException();
}
this.field = field;
int coefficientsLength = coefficients.length;
if (coefficientsLength > 1 && coefficients[0] == 0) {
// Leading term must be non-zero for anything except the constant polynomial "0"
int firstNonZero = 1;
while (firstNonZero < coefficientsLength && coefficients[firstNonZero] == 0) {
firstNonZero++;
}
if (firstNonZero == coefficientsLength) {
this.coefficients = field.getZero().coefficients;
} else {
this.coefficients = new int[coefficientsLength - firstNonZero];
System.arraycopy(coefficients,
firstNonZero,
this.coefficients,
0,
this.coefficients.length);
}
} else {
this.coefficients = coefficients;
}
}
|
606bb29d-2ef5-4ea5-8bf8-2b12d9b95705
| 1 |
private void preencheTabela(List<UsuarioSistema> lista){
this.modelo = new DefaultTableModel();
modelo.addColumn("Id");
modelo.addColumn("Nome");
modelo.addColumn("Cpf");
modelo.addColumn("Rg");
modelo.addColumn("Data de Nascimento");
modelo.addColumn("Usuario");
/*modelo.addColumn("Endereços");
modelo.addColumn("Telefones");
modelo.addColumn("Emails");
*/
for(UsuarioSistema u : lista){
Vector v = new Vector();
v.add(0,u.getIdUsuario());
v.add(1,u.getNome());
v.add(2,u.getCpf());
v.add(3,u.getRg());
v.add(4,u.getDataNascimento());
v.add(5,u.getUsuario());
modelo.addRow(v);
}
this.tblUsuariosSistema.setModel(modelo);
tblUsuariosSistema.repaint();
}
|
f28b1720-ecec-41f5-926b-306301e4a772
| 1 |
private int getNumero(int[] datos, int i) {
if (i < datos.length) {
return datos[i];
} else {
return 0;
}
}
|
0da69e3f-938e-4bff-b041-54b045393ab9
| 6 |
public static Collection<IndexCommit> listCommits(Directory dir) throws IOException {
final String[] files = dir.listAll();
Collection<IndexCommit> commits = new ArrayList<IndexCommit>();
SegmentInfos latest = new SegmentInfos();
latest.read(dir);
final long currentGen = latest.getGeneration();
commits.add(new ReaderCommit(latest, dir));
for(int i=0;i<files.length;i++) {
final String fileName = files[i];
if (fileName.startsWith(IndexFileNames.SEGMENTS) &&
!fileName.equals(IndexFileNames.SEGMENTS_GEN) &&
SegmentInfos.generationFromSegmentsFileName(fileName) < currentGen) {
SegmentInfos sis = new SegmentInfos();
try {
// IOException allowed to throw there, in case
// segments_N is corrupt
sis.read(dir, fileName);
} catch (FileNotFoundException fnfe) {
// LUCENE-948: on NFS (and maybe others), if
// you have writers switching back and forth
// between machines, it's very likely that the
// dir listing will be stale and will claim a
// file segments_X exists when in fact it
// doesn't. So, we catch this and handle it
// as if the file does not exist
sis = null;
}
if (sis != null)
commits.add(new ReaderCommit(sis, dir));
}
}
return commits;
}
|
025304c5-a03c-4c5e-a1e5-b27c7c0e4637
| 1 |
public Document buildUpdateStatus(Document document, Element root, ReversiBoard board, boolean update){
Element currentPlayerElement = document.createElement("update_status");
String updateString;
if(update) updateString = "completed";
else updateString = "failed";
Text text = document.createTextNode(updateString);
currentPlayerElement.appendChild(text);
root.appendChild(currentPlayerElement);
return document;
}
|
d7936819-b650-4487-ba31-73a2a9bc778c
| 4 |
private boolean isCastleLocationSafe(int baseYPos, int direction){
Position rookInitPos = (direction == 1) ? new Position(7, baseYPos) : new Position(0, baseYPos);
int xPos = 3+direction;
Position gonnaInspectPos = new Position(xPos, baseYPos);
while(!rookInitPos.equals(gonnaInspectPos)){
//킹과 캐슬 사이는 비어있으며, 적의 공격과 이동이 불가해야 한다.
if(Board.chessBoard.containsKey(gonnaInspectPos)) return false;
if(Board.moveAblePosSet.contains(gonnaInspectPos)) return false;
xPos+=direction;
gonnaInspectPos = new Position(xPos, baseYPos);
}
return true;
}
|
116c512f-3ada-48e0-b3a2-255c0442ef20
| 5 |
protected void loadMap(String name, String fileName, HashMap<String, String> map) {
if (verbose) Timer.showStdErr("Loading " + name + " from '" + fileName + "'");
int i = 1;
for (String line : Gpr.readFile(fileName).split("\n")) {
String rec[] = line.split("\t");
String id = rec[0];
String componentId = rec[1];
map.put(id, componentId);
if (verbose) Gpr.showMark(i++, SHOW_EVERY);
}
if (verbose) System.err.println("");
if (verbose) Timer.showStdErr("Total objects loaded: " + map.size());
}
|
2448ab61-7a94-4bfa-8c8e-9ac1c4dfbf72
| 9 |
public void actionPerformed(ActionEvent e){
String option = e.getActionCommand();
if(option.equals("add another")){
JTextField TxtF = new JTextField(10);
TxtF.setFont(Themes.componentsFont);
TxtF.setAlignmentX(Component.CENTER_ALIGNMENT);
tagsPanel.add(TxtF);
JTextField TxtF2 = new JTextField(10);
TxtF2.setFont(Themes.componentsFont);
TxtF2.setAlignmentX(Component.CENTER_ALIGNMENT);
tagsPanel.add(TxtF2);
tagsPanel.revalidate();
int height = (int)tagsPanel.getPreferredSize().getHeight();
scrollPane.getVerticalScrollBar().setValue(height+20);
}
else if(option.equals("done")){
ArrayList<String> types = new ArrayList<String>();
ArrayList<String> vals = new ArrayList<String>();
boolean typeDone=false;
for (Component c : tagsPanel.getComponents()) {
if (c instanceof JTextField) {
if(!typeDone){
types.add(((JTextField) c).getText());
typeDone=true;
}
else{
vals.add(((JTextField) c).getText());
typeDone=false;
}
}
}
for(int i=0;i<types.size();i++){
if(!types.get(i).equals("")&&!vals.get(i).equals("")){
boolean done = control.addTag(filename, types.get(i), vals.get(i));
if(!done){
final JFrame error = new JFrame("Important Message!");
JOptionPane.showMessageDialog(error, "Tag already exists for "+filename+" "+types.get(i)+":\""+vals.get(i)+"\"");
}
else{
final JFrame error = new JFrame("Important Message!");
JOptionPane.showMessageDialog(error, "Tag added: "+types.get(i)+":\""+vals.get(i)+"\"");
}
}
}
addTagsPopUp.this.photoDisplay.save();
addTagsPopUp.this.setVisible(false);
}
}
|
e871db00-51cb-467f-8cd7-c6affdc348a3
| 4 |
public void acquaireIngridient(Dish dish) {
Vector<Ingredient> dishIngredients= dish.getDishIngredients();
for (int i= 0; i < dishIngredients.size(); i++) {
boolean found= false;
int location= 0;
for (int j= 0; ((!found) && (j < this._availableIngredients.size())); j++) {
found= (this._availableIngredients.elementAt(j)).isSameIngredient(dishIngredients.elementAt(i));
if (found)
location= j;
}
int dishIngredientQuantity= dishIngredients.elementAt(i).getQuantity();
this._availableIngredients.elementAt(location).acquire(dishIngredientQuantity);
}
}
|
a8b5a6b1-b71f-4800-85c7-06a626cdbe67
| 0 |
public T getSecond() { return second; }
|
2b784c42-b269-4c0b-a9da-032078a38d15
| 2 |
private String get(String variable, String lookahead) {
try {
return (String) pane.table.get(variable, lookahead).first();
} catch (IllegalArgumentException e) {
return null;
} catch (NoSuchElementException e) {
return null;
}
}
|
c4a847e4-6159-4270-8e71-3016f8f4eb80
| 5 |
private void drawTile(Tile t, Graphics g, int x, int y, int width,
int height) {
if (t.isCollidable()) {
g.setColor(ColorDirector.getCurrentPrimary((t.isSlowWall() ? ColorType.SLOW_WALL
: ColorType.WALL)));
g.fillRect(x, y, width, height);
if (x < scaledXDistLeft || x > scaledXDistRight)
return;
g.setColor(ColorDirector.getCurrentSecondary((t.isSlowWall() ? ColorType.SLOW_WALL
: ColorType.WALL)));
g.drawRect(x, y, width, height);
}
}
|
f1f7de71-2073-4880-b0ed-4cef354145c6
| 1 |
public void addQuizToDB() {
try {
String statement = new String("INSERT INTO " + DBTable
+ " (name, url, description, category, userid, israndom, isonepage, opfeedback, oppractice, raternumber, rating)"
+ " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
PreparedStatement stmt = DBConnection.con.prepareStatement(statement, new String[] {"qid"});
stmt.setString(1, name);
stmt.setString(2, quizURL);
stmt.setString(3, description);
stmt.setString(4, category);
stmt.setInt(5, creator.userID);
stmt.setBoolean(6, isRandom);
stmt.setBoolean(7, isOnepage);
stmt.setBoolean(8, opFeedback);
stmt.setBoolean(9, opPractice);
stmt.setInt(10, raterNumber);
stmt.setDouble(11, totalRating);
stmt.executeUpdate();
ResultSet rs = stmt.getGeneratedKeys();
rs.next();
quizID = rs.getInt("GENERATED_KEY");
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
|
e3ad1414-ef7c-4a7e-ba79-6cae321c5c1e
| 6 |
public boolean dealerHit() {
if (this.hand.totalvalues()[0] < 17 && this.hand.totalvalues()[0] == this.hand.totalvalues()[1]) {
return true;
} else if (this.hand.totalvalues()[0] <= 17 && this.hand.totalvalues()[0] != this.hand.totalvalues()[1]) {
return true;
} else if (this.hand.totalvalues()[1] < 17 && this.hand.totalvalues()[0] != this.hand.totalvalues()[1]) {
return true;
}
return false;
}
|
f37359bc-32f9-4967-8a4f-78a97b8e0bee
| 4 |
public final synchronized boolean readBoolean(){
boolean retB = true;
String retS = this.readWord();
if(retS.equals("false") || retS.equals("FALSE")){
retB = false;
}
else{
if(retS.equals("true") || retS.equals("TRUE")){
retB = true;
}
else{
throw new IllegalArgumentException("attempted input neither true nor false");
}
}
return retB;
}
|
d84f3573-09f7-45fb-8822-54895a5c376d
| 8 |
private boolean searchUpForPrevSupersetNode( Node node, K key, Object[] ret ) {
if( node.mLeft != null && mComp.compareMaxes( key, node.mLeft.mMaxStop.mKey ) <= 0 ) {
ret[0] = node.mLeft;
return false;
}
while( node.mParent != null ) {
if( node == node.mParent.mLeft ) {
node = node.mParent;
} else {
node = node.mParent;
// If we're coming from the right path, it means we haven't
// checked the current node or left subtree.
if( mComp.compareMins( key, node.mKey ) >= 0 ) {
if( mComp.compareMaxes( key, node.mKey ) <= 0 ) {
ret[0] = node;
return true;
}
}
// Check if left subtree might contain mKey.
if( node.mLeft != null && mComp.compareMaxes( key, node.mLeft.mMaxStop.mKey ) <= 0 ) {
// Request downward search on left subtree.
ret[0] = node.mLeft;
return false;
}
}
}
// Search completed.
ret[0] = null;
return true;
}
|
15fd271d-1563-4c2b-bed5-3a7f0a1f213c
| 0 |
void foo3() {
}
|
1047ed44-c93c-441e-8469-d0d95d166fe5
| 0 |
public void displayScreen(Screen screen) {
this.currentScreen = screen;
}
|
88904aaf-a728-4ddb-8f6b-2487bcee3a38
| 2 |
static boolean isZin(String reeks) {
boolean spatie = false;
for(int i = 0; i < reeks.length(); i++) {
if(reeks.charAt(i) == ' ') {
spatie = true;
break;
}
}
return spatie;
}
|
83fba600-c1eb-41b6-a49a-9d28703f6ccd
| 9 |
public boolean move(int dx, int dy, Set<RenderObject> allObjects) {
// Did we encounter a collision during the movement?
boolean collision = false;
if (hasCollision) {
// We need to check for collision.
// Create a set for all possible collision targets.
Set<RenderObject> collisionTargets = new HashSet<RenderObject>();
// Add all _other_ objects that have collision.
for (RenderObject object : allObjects) {
if (object != this && object.hasCollision) {
collisionTargets.add(object);
}
}
// Simple algorithm:
// 1. Calculate the number of movement steps.
int steps = Math.max(Math.abs(dx), Math.abs(dy));
// Calculate the speed in the two dimensions.
// This can be fractions, thus we need to use floats.
float speedX = ((float) dx) / steps;
float speedY = ((float) dy) / steps;
// As we are working with floats for the speed, we need
// to use floats for the position too.
float positionX = this.x;
float positionY = this.y;
// 2. Move "step by step" into the desired direction.
for (int step = 0; step < steps; step++) {
// Perform the next step.
positionX += speedX;
positionY += speedY;
// Update the position of this object.
this.x = Math.round(positionX);
this.y = Math.round(positionY);
// Check if there is a collision now.
for (RenderObject object : collisionTargets) {
if (overlapsWithObject(object)) {
// There is a collision!
collision = true;
// Exit the loop of checking for collisions directly.
break;
}
}
if (collision) {
// There was a collision!
// Move one step back, to the last position, because
// there was no collision there.
positionX -= speedX;
positionY -= speedY;
// Set the positions to this last position.
this.x = Math.round(positionX);
this.y = Math.round(positionY);
// Exit the moving loop, since we have a collision and we
// cannot move further.
break;
}
}
} else {
// This object has no collision, just update the coordinates.
this.x += dx;
this.y += dy;
}
if (collision) {
Log.info("There was a collision!");
}
return collision;
}
|
0d3406c0-63d9-4897-aca7-838ddc31a2b3
| 0 |
private void hidePanels(Container lastOpen)
{
buttonPanel.setVisible(false);
manualPanel.setVisible(false);
programmerFrame.setVisible(false);
lastOpen.setVisible(true);
}
|
20053f3d-a26a-45d3-8b82-d6f47817dfa3
| 9 |
private static EntropyDecoder getDecoder(String name, InputBitStream ibs)
{
switch(name)
{
case "FPAQ":
case "CM":
case "PAQ":
case "TPAQ":
return new BinaryEntropyDecoder(ibs, getPredictor(name));
case "HUFFMAN":
return new HuffmanDecoder(ibs);
case "ANS":
return new ANSRangeDecoder(ibs);
case "RANGE":
return new RangeDecoder(ibs);
case "EXPGOLOMB":
return new ExpGolombDecoder(ibs, true);
case "RICEGOLOMB":
return new RiceGolombDecoder(ibs, true, 4);
default:
System.out.println("No such entropy decoder: "+name);
return null;
}
}
|
b664378e-4697-4f2e-8757-134b6fff9c48
| 2 |
public void done() {
done = false;
SwingUtilities.invokeLater(new Runnable() {
public void run() {
closebtn.setEnabled(true);
status.setText("The error has been reported.");
pack();
}
});
synchronized(this) {
try {
while(!done)
wait();
} catch(InterruptedException e) {
throw(new Error(e));
}
}
errorsent();
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.