method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
76edfcc3-b43f-4c4e-a109-d6652fb868d2 | 4 | @Override
public boolean startVideoCutting(List<VideoSection> videoSections, File inputVideo) {
// Add "_out" to the output file name before extension
String inputFilePath = inputVideo.getAbsolutePath();
String outputFilePath =
inputFilePath.substring(0, inputFilePath.lastIndexOf("."))
+ "_out"
+ inputFilePath.substring(inputFilePath.lastIndexOf("."), inputFilePath.length());
final File outputVideo = new File(outputFilePath);
// Create output file
if (outputVideo.exists())
outputVideo.delete();
try {
outputVideo.createNewFile();
} catch (IOException e) {
mediator.reportActionFailed("Failed to create output file.");
System.out.println(e.getMessage());
e.printStackTrace();
}
// Filter only section to be cut
final List<VideoSection> sectionToSilence = new LinkedList<VideoSection>();
for(VideoSection section : videoSections) {
if (section.getCut())
sectionToSilence.add(section);
}
(processThread = createProcessingThread(inputVideo, outputVideo, mediator, sectionToSilence)).start();
return true;
} |
e248e9c6-e52a-4f91-a040-eaaf37169879 | 2 | @Override
public void draw(Graphics2D g,float interpol) {
if (!isConstructed)
construct();
// g.setColor(Color.WHITE);
// g.drawRect((int)position.x, (int)position.y, dims.width, dims.height);
for (Item i : items) {
i.draw(g,interpol);
}
} |
838cedff-79f8-45e9-bc93-6d4d89cdca5c | 2 | public String retry(String q, ArrayList<String> prop, ArrayList<String> loc){
String newQ = q;
Iterator<String> keys = commonErrors.keySet().iterator();
while (keys.hasNext()){
String current = keys.next();
int index = q.indexOf(current);
if (index != -1){
newQ = q.replaceAll(current, commonErrors.get(current));
}
}
return reply2(newQ.trim(), prop, loc);
} |
283d4c01-aa02-43c2-89b7-cf8484619ef8 | 9 | public void update() {
maybeAddPher();
move(map.getSurround(xy));
if(map.home(xy)) {
state = AntState.Searching;
incr = state.getIncrement();
dir = Ordinal.getRandomDirection();
}else {
Food f = map.getFood(xy);
if(f != null && f.canTake() && carrying < CARRY_LIMIT) {
carrying += f.take();
if(state != AntState.Returning) {
dir = dir.flipDirection();
}
state = AntState.Returning;
incr = state.getIncrement();
}
}
if(carrying > 0.0f &&
(map.home(xy) ||
state == AntState.Returning && steps < 0)) {
incr = Math.max(1.0f, incr * 0.8f);
dir = Ordinal.getRandomDirection();
state = AntState.Searching;
steps = 0;
map.addFood((Point) xy.clone(),carrying);
carrying = 0;
}
} |
9a01f22c-4660-4be2-a89d-7c8731677cd0 | 5 | private void createButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_createButtonActionPerformed
try {
String subject = subjectTextField.getText();
String description = descriptionTextField.getText();
ArrayList<String> options = new ArrayList(Arrays.asList(optionTextField.getText().split(",")));
for(String option : options) {
option = option.trim();
}
String priority = priorityComboBox.getSelectedItem().toString();
int month = Integer.valueOf(monthComboBox.getSelectedItem().toString());
int day = Integer.valueOf(dayComboBox.getSelectedItem().toString());
int year = Integer.valueOf(yearComboBox.getSelectedItem().toString());
Date expiration = new Date(year, month, day);
boolean success = false;
if (this.proposal != null && this.proposal.getId() > -1) {
this.proposal.setDescription(description);
this.proposal.setSubject(subject);
this.proposal.setOptions(options);
this.proposal.setExpirationDate(expiration);
this.proposal.setOptions(options);
this.proposal.setPriority(Proposal.getPriorityLevel(priority));
success = ProposalLogic.updateProposal(this.proposal);
} else {
success = ProposalLogic.createProposal(expiration, subject, description, priority, options);
}
if (success){
JOptionPane.showMessageDialog(this,
"Proposal successfully created!");
FOTE.getMainFrame().loadProposals();
this.dispose();
}
else {
JOptionPane.showMessageDialog(this,
"Proposal creation failed!");
}
} catch (java.lang.NumberFormatException e) {
// TODO : Show error on input
}
}//GEN-LAST:event_createButtonActionPerformed |
b5331630-22c1-437d-9bbc-ab61b72a798d | 4 | public static int getPercentToLevel(final int index, final int endLvl) {
if (index > SKILL_NAMES.length - 1) {
return -1;
}
final int lvl = Skills.getRealLevel(index);
if (lvl == 99 || endLvl > 99) {
return 100;
}
final int xpTotal = Skills.XP_TABLE[endLvl] - Skills.XP_TABLE[lvl];
if (xpTotal == 0) {
return 0;
}
final int xpDone = Skills.getExperience(index) - Skills.XP_TABLE[lvl];
return 100 * xpDone / xpTotal;
} |
0338d513-ac6a-43a5-96fb-75fe479fb264 | 5 | public boolean onCommand(CommandSender sender, Command command,
String label, String[] args) {
if (!plugin.hasPerm(sender, "clear", true)) {
sender.sendMessage(ChatColor.YELLOW
+ "You do not have permission to use /" + label);
return true;
}
if (args.length == 0)
return false;
if (plugin.playerMatch(args[0]) != null) {
Player p = plugin.getServer().getPlayer(args[0]);
p.getInventory().clear();
if (plugin.isPlayer(sender)) {
Player player = (Player) sender;
player.sendMessage(CraftEssence.premessage + p.getName()
+ "'s inventory is cleared.");
p.sendMessage(ChatColor.GRAY + player.getName()
+ " cleared your inventory");
} else {
plugin.logger(Level.INFO, p.getName()
+ "'s inventory is cleared.");
p.sendMessage(ChatColor.GRAY
+ "Your inventory has been cleared.");
}
} else {
if (plugin.isPlayer(sender)) {
Player player = (Player) sender;
player.sendMessage(CraftEssence.premessage
+ "Player is offline or not found");
} else {
plugin.logger(Level.INFO, "Player is offline or not found");
}
}
return true;
} |
c6064064-548c-47ea-a99b-a5d9178801de | 2 | @Override
public void run() {
String[] datos = new String[14];
String[] temp = new String[2];
try {
URL pagina = new URL("http://chapuzas.comocreartuweb.es/documentos/datos.txt");
HttpURLConnection con = (HttpURLConnection) pagina.openConnection();
con.connect();
InputStreamReader in = new InputStreamReader((InputStream) con.getContent());
BufferedReader buff = new BufferedReader(in);
for (int i = 0; i < 14; i++) {
temp = buff.readLine().split(" ");
datos[i] = temp[1];
}
txtSalarioBase.setText(datos[0]);
txtTransporte.setText(datos[1]);
txtVestuario.setText(datos[2]);
txtPeligrosidad.setText(datos[3]);
txtTrienio.setText(datos[4]);
txtQuinquenio.setText(datos[5]);
txtHoraNocturna.setText(datos[6]);
txtHoraFestiva.setText(datos[7]);
txtHoraArma.setText(datos[8]);
txtNochebuena.setText(datos[9]);
txtKilometraje.setText(datos[10]);
txtRadio.setText(datos[11]);
txtRadioBasica.setText(datos[12]);
txtHorasConvenio.setText(datos[13]);
} catch (IOException ioe) {
JOptionPane.showMessageDialog(null,
"Chungo, Ha fallado la conexion",
"Error",
JOptionPane.ERROR_MESSAGE);
} finally {
btnObtenerDatos.setText("Obtener datos");
hilo = null;
}
} |
0520ea1e-353f-4a11-99d9-5a057fbac5cd | 4 | public boolean update()
{
if(Keyboard.getButton() != 1 && show == 2)
{
show = 0;
return true;
}
show = 0;
int mx = Keyboard.getMouseX() - Frame.transx;
int my = Keyboard.getMouseY() - Frame.transy;
if(Collision.recToRect(mx, my, 0, 0, x, y, look[show].getWidth(), look[show].getHeight()))
{
if(Keyboard.getButton() == 1) show = 2;
else show = 1;
}
return false;
} |
44519714-3708-46eb-b1ff-2a223cb0e4cc | 7 | final char[] optimizedCurrentTokenSource2() {
//try to return the same char[] build only once
char[] src = this.source;
int start = this.startPosition;
char c0 , c1;
int hash = (((c0=src[start]) << 6) + (c1=src[start+1])) % TableSize;
char[][] table = this.charArray_length[0][hash];
int i = newEntry2;
while (++i < InternalTableSize) {
char[] charArray = table[i];
if ((c0 == charArray[0]) && (c1 == charArray[1]))
return charArray;
}
//---------other side---------
i = -1;
int max = newEntry2;
while (++i <= max) {
char[] charArray = table[i];
if ((c0 == charArray[0]) && (c1 == charArray[1]))
return charArray;
}
//--------add the entry-------
if (++max >= InternalTableSize) max = 0;
char[] r;
System.arraycopy(src, start, r= new char[2], 0, 2);
//newIdentCount++;
return table[newEntry2 = max] = r; //(r = new char[] {c0, c1});
} |
2ab6f2a2-cb19-4429-9ec5-480bba9ab7ba | 8 | public boolean isNavigationEvent(ColumnViewer viewer, Event event) {
switch (event.keyCode) {
case SWT.ARROW_UP:
case SWT.ARROW_DOWN:
case SWT.ARROW_LEFT:
case SWT.ARROW_RIGHT:
case SWT.HOME:
case SWT.PAGE_DOWN:
case SWT.PAGE_UP:
case SWT.END:
return true;
default:
return false;
}
} |
525b970b-670f-4f3b-85fb-28000ce46d5f | 5 | public static void main(final String[] args) {
final File file = new File("D:/Program Files (x86)/Run 8 Studios/Run 8 Train Simulator/Content/RailVehicles");
for (String name : file.list()) {
if (name.startsWith("R8_Boxcar_50ft_PlateF_") ||
name.startsWith("R8_C14Hopper_") ||
name.startsWith("R8_Pig_") ||
name.startsWith("R8_Reefer_PCF_57_"))
System.out.print("\"" + name + "\", ");
}
} |
6ed06929-f327-48dc-a47c-7bb2b46ffb31 | 1 | public void push(int e) {
if(len >= capacity) {
throw new IllegalStateException("Error: capacity is bigger that len");
}
heap[len] = e;
len++;
bubbleUp(len - 1);
} |
06854a43-4bdb-41bc-be52-49c2dd56c783 | 3 | @Override
public int compareTo(Object o) {
if (o instanceof CycNumber) {
final CycNumber other = (CycNumber) o;
final Class thisNumberClass = this.number.getClass();
if (thisNumberClass.equals(other.number.getClass())
&& Comparable.class.isAssignableFrom(thisNumberClass)) {
return ((Comparable)this.number).compareTo((Comparable)other.number);
} else {
return this.doubleValue().compareTo(other.doubleValue());
}
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
} |
344c88f0-8ebf-4d71-b4d7-8de5b77833ac | 1 | public boolean hasNoJumps() {
return successors.size() == 0 && predecessors.size() == 0;
} |
e5292b6e-2a1b-4171-9697-85a5a318a956 | 5 | private void backTrackToLambda()
{
if (myLambdaStepMap==null)
return;
int index=0;
while (index<myAnswer.size())
{
for (ArrayList <Production> key: myLambdaStepMap.keySet())
{
if (myLambdaStepMap.get(key).equals(myAnswer.get(index)))
{
//System.out.println("Found it = "+key);
//System.out.println("For = "+myAnswer.get(index));
myAnswer.remove(index);
int c=0;
for (Production p : key)
{
myAnswer.add(index+c, p);
c++;
}
index=index+key.size()-1;
}
}
index++;
}
// System.out.println("After Backtracking Lambda = "+myAnswer);
} |
9f4501e7-8b70-4a90-b3a2-0a99412bf965 | 3 | public CycList randomPermutation() {
final Random random = new Random();
int randomIndex = 0;
final CycList remainingList = (CycList) this.clone();
final CycList permutedList = new CycList();
if (this.size() == 0) {
return remainingList;
}
while (true) {
if (remainingList.size() == 1) {
permutedList.addAll(remainingList);
return permutedList;
}
randomIndex = random.nextInt(remainingList.size() - 1);
permutedList.add(remainingList.get(randomIndex));
remainingList.remove(randomIndex);
}
} |
3ae7e85e-e924-4498-9439-c97e30169df0 | 0 | public RandomListNode(int x){
this.label = x;
} |
48cf0d16-c2d1-4f5c-85e0-ac2a79cb7b12 | 9 | public void kickPlayerFromClan(Client c, String name) {
if (!isOwner(c)) {
c.sendMessage("You do not have the power to kick players from this clan chat!");
return;
}
if (c.playerName.equalsIgnoreCase(name)){
c.sendMessage("You may not kick yourself from a clan chat!");
return;
}
if (c.clanId < 0) {
c.sendMessage("You are not in a clan.");
return;
}
for (int i = 0; i < Config.MAX_PLAYERS; i++) {
if (Server.playerHandler.players[i] != null) {
if (Server.playerHandler.players[i].playerName.equalsIgnoreCase(name)) {
Client c2 = (Client)Server.playerHandler.players[i];
if(c2.playerRights >= 2){
c.sendMessage("You may @red@NOT@bla@ kick an admin from you clan!");
c2.sendMessage(c.playerName+" has tried to kick you from his/her clan.");
return;
}
c2.clanId = -1;
c2.sendMessage("You have been kicked from "+clans[c.clanId].name+" by "+c.playerName);
c2.getPA().clearClanChat();
c.sendMessage("You have kicked "+c2.playerName+" from your clan.");
for (int j = 0; j < clans[c.clanId].members.length; j++) {
if (clans[c.clanId].members[j] == i) {
clans[c.clanId].members[j] = -1;
}
}
}
}
}
updateClanChat(c.clanId);
} |
35e216bf-b3a3-4c6d-b62e-7ab8ca73313e | 6 | @Override
public List<DataRow> select(DataRow parameters) {
String statement = "SELECT * FROM " + parameters.getTableName();
if(!parameters.isEmpty())
{
statement += " WHERE ";
}
boolean isFirst = true;
for(DataCell cell : parameters.row)
{
if(isFirst)
{
isFirst = false;
statement += cell.getName() + " = '" + cell.getValue() + "'";
} else {
statement += " AND " + cell.getName() + " = '" + cell.getValue() + "'";
}
}
List<DataRow> result = new LinkedList<>();
try
{
Statement stat = dbConnection.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stat.executeQuery(statement);
rs.beforeFirst();
while(rs.next())
{
DataRow newRow = new DataRow();
newRow.setTableName(parameters.getTableName());
ResultSetMetaData rsmd = rs.getMetaData();
int columnCount = rsmd.getColumnCount();
for(int i = 1; i <= columnCount; i++)
{
newRow.addAttribute(rsmd.getColumnName(i), rs.getString(i));
}
newRow.setName(newRow.getAttribute("name").getValue());
result.add(newRow);
}
return result;
} catch(Exception e) {
ErrorDialog errorDialog = new ErrorDialog(true, "Nastąpił błąd podczas wykonywania select w bazie danych:\n" + e.getMessage(), "SqlServerLocalDatabaseConnector", "select", "parameters, statement");
errorDialog.setVisible(true);
return null;
}
} |
75251c32-7e07-482e-9836-0f40468500aa | 4 | public static SessionState sessionRead(String sessionID, int versionNum, Server server) {
SessionState session = null;
try {
DatagramSocket RPCSocket = new DatagramSocket();
RPCSocket.setSoTimeout(1000);
String callID = UUID.randomUUID().toString(); // A unique id for this call
// Prep the information to be sent
String tempSend = callID + "^" + SESSIONREAD_CODE + "^" + sessionID + "^" + versionNum;
byte[] outBuffer = marshal(tempSend);
DatagramPacket sendPacket = new DatagramPacket(outBuffer, outBuffer.length, server.ip, server.port);
RPCSocket.send(sendPacket);
// The packet has been sent, now wait for the server to reply
byte[] inBuffer = new byte[4096];
DatagramPacket receivedPacket = new DatagramPacket(inBuffer, inBuffer.length);
String response = null;
try {
do {
receivedPacket.setLength(inBuffer.length);
RPCSocket.receive(receivedPacket);
response = RPCClient.unmarshal(inBuffer);
System.out.println(response);
// Parse the response into a SessionState
String[] responseSplit = response.split("\\^");
session = new SessionState(sessionID, versionNum, null);
session.setVersionNumber(Integer.parseInt(URLDecoder.decode(responseSplit[1], "UTF-8")));
session.setMessage(URLDecoder.decode(responseSplit[2], "UTF-8"));
session.setNewExpirationTime(URLDecoder.decode(responseSplit[3], "UTF-8"));
} while (response == null || !(response.split("\\^")[0].equals(callID)));
} catch (IOException e) {
e.printStackTrace();
return null;
}
return session;
} catch (Exception e) {
e.printStackTrace();
return null;
}
} |
4d84de89-ef39-4820-b297-2a02e74fc0fd | 7 | static String toHex4ByteString(int i) {
String hex = Integer.toHexString(i);
if (hex.length() == 1)
return "0000000" + hex;
if (hex.length() == 2)
return "000000" + hex;
if (hex.length() == 3)
return "00000" + hex;
if (hex.length() == 4)
return "0000" + hex;
if (hex.length() == 5)
return "000" + hex;
if (hex.length() == 6)
return "00" + hex;
if (hex.length() == 7)
return "0" + hex;
return hex;
} |
4488d5b0-d2f7-411f-b2f7-dd7f0b322d44 | 1 | void moveX(boolean right) {
if (right)
x += speed;
else x -= speed;
} |
a5a169af-45f0-4d53-8b12-56db8241a41c | 1 | public Instrumenter(Set<Local> set){//SootMethod m, Set<Local> set){//Map<Local, Set<Unit>> map) {
// TODO Auto-generated constructor stub
//method = m;
// ins_map = map;
// factory_already_created = new HashSet<String>();
getUtilClasses();
//for(Map.Entry<Local, Set<Unit>> entry: ins_map.entrySet()){
for(Local l: set){
//Local l = entry.getKey();
SootClass c = Scene.v().getSootClass(l.getType().toString());
// if(createFactoryClass(c))
modifyObjectClass(c);
}
} |
fc61d63a-9e92-492f-9047-ef91722cd55d | 2 | private final Element getArtistListNode(String artistName)
throws GetHttpException, MusicbrainzUrlException, CreateDocException {
String content= "";
content= this.getHttp.getWebPageAsString(MusicbrainzUrl.getMbArtistUrl(artistName));
if(content.equals(""))
return null;
this.artistDoc= CreateDoc.create(content);
//if the count is zero, no artist was found.
Element artistListNode= (Element) this.artistDoc.getElementsByTagName("artist-list").item(0);
Integer count= Integer.valueOf(artistListNode.getAttributes().getNamedItem("count").getNodeValue());
if(count.intValue() == 0)
return null;
else
return artistListNode;
} |
318a531a-047a-43bc-9f70-8ab6bec0179e | 0 | public void setCarriedKeyName(String value) {
this.carriedKeyName = value;
} |
55f6d248-874f-4fe5-a8cd-fc4f0ccb422e | 5 | public void createLetters(int numberOfLetters, boolean randomOrder) {
Array<Letter> letters = this.languageController.giveACombination(numberOfLetters);
letters.shuffle();
float circleSpeed = 10;// previous 50
for (int i = 0; i < numberOfLetters; i++) {
// First we create a body definition
BodyDef bodyDef = new BodyDef();
// We set our body to dynamic, for something like ground which
// doesnt
// move we would set it to StaticBody
bodyDef.type = BodyType.DynamicBody;
float x = 300;
float y = 300;
if (randomOrder) {
x = Math.round(Math.random() * 500 + 100);
y = Math.round(Math.random() * 300 + 100);
}
// Set our body's starting position in the world
// float x = Math.round(Math.random() * Gdx.graphics.getWidth()
// +20);
// ;
// float y = Math.round(Math.random() * Gdx.graphics.getHeight()
// +20-100);
// float x = Math.round(Math.random() * 600 +100);
//
// float y = Math.round(Math.random() * 400 + 100);
if (this.heroController != null && this.heroController.getHero() != null) {
while (this.heroController.getHero().getBoundingRectangle().contains(x, y)) { // to
// avoid
// that
// a
// letter
// collides
// with
// the
// hero
// in
// the
// starting
// position
x = Math.round(Math.random() * 500 + 100);
y = Math.round(Math.random() * 300 + 100);
}
}
bodyDef.position.set(x / WORLD_SCALE, y / WORLD_SCALE);
float randomAngle = (float) (2f * Math.random() * Math.PI);
bodyDef.angle = randomAngle;
// bodyDef.linearVelocity.set(0, -100000000000f);
bodyDef.gravityScale = 200000;
// Create our body in the world using our body definition
Body body = this.round.getBox2DWorld().createBody(bodyDef);
float vx = (float) (circleSpeed * Math.cos(randomAngle));
float vy = (float) (circleSpeed * Math.sin(randomAngle));
body.setLinearVelocity(vx, vy);
body.setAngularVelocity(0.2f);// previous 0.5
Letter letter = letters.get(i);
body.setUserData(letter);
// Create a circle shape and set its radius to 6
CircleShape circle = new CircleShape();
circle.setRadius(10f / WORLD_SCALE);
// Create a fixture definition to apply our shape to
FixtureDef fixtureDef = new FixtureDef();
fixtureDef.shape = circle;
fixtureDef.density = 1f;
fixtureDef.friction = 0f;
fixtureDef.restitution = 1f; // Make it bounce a little bit
// Create our fixture and attach it to the body
Fixture fixture = body.createFixture(fixtureDef);
// Remember to dispose of any shapes after you're done with them!
// BodyDef and FixtureDef don't need disposing, but shapes do.
circle.dispose();
this.round.addLetter(letter);
}
} |
22c5e01b-8b6c-4218-b8b0-b63dd430f191 | 8 | public Object getValueAt(int rowIndex, int columnIndex) {
switch(columnIndex) {
case 0 : return list.get(rowIndex).getNota();
case 1 : return list.get(rowIndex).getNama();
case 2 : return list.get(rowIndex).getPewangi();
case 3 : return list.get(rowIndex).getBerat();
case 4 : return list.get(rowIndex).getMasuk();
case 5 : return list.get(rowIndex).getAmbil();
case 6 : return list.get(rowIndex).getHarga();
case 7 : return list.get(rowIndex).getKet();
default: return null;
}
} |
b74e7a76-000f-4033-9cd6-286b4cfd44f8 | 9 | public Ability(World world){
this.world = world;
mainAbilityThread = new Thread(new Runnable(){
@Override
public void run() {
// TODO Auto-generated method stub
while(OrbGame.isRunning) {
Gdx.app.log(log, "Run method is getting called and booleans are being checked");
//checks if the ability is cooling down
if(isCoolingDown) {
isCooledDown = false;
if(currentTimeCoolDown - startTime >= (coolDownTime * NANO)) {
isCoolingDown = false;
isCooledDown = true;
Gdx.app.log(log, "ability is cooled down");
}
currentTimeCoolDown = TimeUtils.nanoTime();
}
if(!needsLocation) {
if(isClicked) {
Gdx.app.log(log, "ability doesn't need a location and is clicked");
isReady = true;
isCoolingDown = true;
}
}else{
if(hasLocation && isClicked){
Gdx.app.log(log, "ability needs a location, has a location, and is clicked");
isClicked = false;
isReady = true;
isCoolingDown = true;
}
}
//stopAbility will make this false
if(isReady) {
Gdx.app.log(log, "ability is starting");
startAbility();
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
//Start the thread
mainAbilityThread.start();
} |
7f6a812a-8769-4ac2-8aa7-a71362da7eb1 | 4 | public static void main(String[] args) {
String line = "";
String message = "";
int c;
try {
while ((c = System.in.read()) >= 0) {
switch (c) {
case '\n':
if (line.equals("go")) {
PlanetWars pw = new PlanetWars(message);
DoTurn(pw);
pw.FinishTurn();
message = "";
} else {
message += line + "\n";
}
line = "";
break;
default:
line += (char) c;
break;
}
}
} catch (Exception e) {
StringWriter writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
String stackTrace = writer.toString();
System.err.println(stackTrace);
System.exit(1); //just stop now. we've got a problem
}
} |
90689caf-3964-4aba-8986-76a7093f8afa | 8 | private void parseMap() throws FileNotFoundException {
Scanner scan = new Scanner(ResourceHandler.getLevelFile(levelID + ".map"));
for (int i = 0; i < levelHeight; i++) {
for (int j = 0; j < levelWidth; j++) {
String text = scan.next();
if (text.equals("#"))
map[i][j] = new Stone();
else if (text.equals("&"))
map[i][j] = new Oil();
else if (text.equals("+"))
map[i][j] = new LevelPortal();
else if (text.equals("S"))
map[i][j] = new FastBuff();
else if (text.equals("G"))
map[i][j] = new GhostBuff();
else if (text.equals("T"))
map[i][j] = new Tree();
}
}
scan.close();
} |
d7884705-56dc-4d79-9e4f-3a2744eb099b | 4 | @Override
public void mouseWheelMoved(MouseWheelEvent e) {
int a = e.getWheelRotation();
if (a < 0) {
for(int i = 0; i < -a; i++) {
keys[KeyEvent.VK_UP] = true;
updateStatus();
keys[KeyEvent.VK_UP] = false;
}
}
else if (a > 0) {
for(int i = 0; i < a; i++) {
keys[KeyEvent.VK_DOWN] = true;
updateStatus();
keys[KeyEvent.VK_DOWN] = false;
}
}
} |
41d35e4e-a85a-4263-b394-7bda7daf79b3 | 9 | protected void flush() throws IOException {
assert off > 0;
long min = Long.MAX_VALUE, max = Long.MIN_VALUE;
for (int i = 0; i < off; ++i) {
min = Math.min(values[i], min);
max = Math.max(values[i], max);
}
final long delta = max - min;
int bitsRequired = delta == 0 ? 0 : PackedInts.unsignedBitsRequired(delta);
if (bitsRequired == 64) {
// no need to delta-encode
min = 0L;
} else if (min > 0L) {
// make min as small as possible so that writeVLong requires fewer bytes
min = Math.max(0L, max - PackedInts.maxValue(bitsRequired));
}
final int token = (bitsRequired << BPV_SHIFT) | (min == 0 ? MIN_VALUE_EQUALS_0 : 0);
out.writeByte((byte) token);
if (min != 0) {
writeVLong(out, zigZagEncode(min) - 1);
}
if (bitsRequired > 0) {
if (min != 0) {
for (int i = 0; i < off; ++i) {
values[i] -= min;
}
}
writeValues(bitsRequired);
}
off = 0;
} |
7d856e94-58a9-4dbb-b8fd-ce72e2f28f4e | 3 | public Component getColorDropdown()
{
if (colorDropdown == null)
{
colorDropdown = new JComboBox<Color>();
colorDropdown.setRenderer(new ListCellRenderer<Color>()
{
@Override
public Component getListCellRendererComponent(JList<? extends Color> list, final Color value, int index,
boolean isSelected, boolean cellHasFocus)
{
JLabel label = new JLabel(value.getRed() + ", " + value.getGreen() + ", " + value.getBlue());
label.setIconTextGap(10);
label.setIcon(new Icon()
{
@Override
public void paintIcon(Component c, Graphics g, int x, int y)
{
Graphics2D paint = (Graphics2D) g.create();
paint.setColor(value);
paint.fillRect(2, 2, getIconWidth() - 4, getIconHeight() - 4);
}
@Override
public int getIconWidth()
{
return 16;
}
@Override
public int getIconHeight()
{
return 16;
}
});
return label;
}
});
for (Color color : DEFAULT_COLORS)
{
((DefaultComboBoxModel<Color>) colorDropdown.getModel()).addElement(color);
}
colorDropdown.setSelectedItem(converter.getNonterminatingColor());
colorDropdown.addItemListener(new ItemListener()
{
@Override
public void itemStateChanged(ItemEvent e)
{
converter.setNonterminatingColor((Color) e.getItem());
}
});
}
return colorDropdown;
} |
40953cf5-434a-4fd8-b15b-99469c5bdc55 | 4 | @SuppressWarnings( "unchecked" )
private ByteBuf writeStatusPacket()
{
JSONObject root = new JSONObject();
JSONObject version = new JSONObject();
if(MCListener.pingAppearOffline)
{
version.put("name", "Offline");
version.put("protocol", 0);
}
else
{
version.put("name", "1.8.0");
version.put("protocol", 47);
}
JSONObject players = new JSONObject();
players.put("max", MCListener.pingMaxPlayers);
players.put("online", MCListener.pingCurPlayers);
if(MCListener.pingDescription.length > 0)
{
JSONArray sample = new JSONArray();
for(String line : MCListener.pingDescription)
{
UUID id = UUID.nameUUIDFromBytes(line.getBytes());
JSONObject samplePart = new JSONObject();
samplePart.put("name", line);
samplePart.put("id", id.toString());
sample.add(samplePart);
}
players.put("sample", sample);
}
root.put("version", version);
root.put("players", players);
root.put("description", MCListener.pingMOTD);
if(MCListener.pingIcon != null)
root.put("favicon", MCListener.pingIcon.getIconString());
ByteBuf buffer = Unpooled.buffer();
Utils.writeVarInt(buffer, 0);
Utils.writeString(buffer, root.toJSONString());
return buffer;
} |
fdee73da-ca6c-44b4-a51c-fd879e781919 | 1 | private void emitTabs() {
for (int i = 0; i < mDepth; i++) {
mOut.print('\t');
}
} |
a870eab6-73b2-41f5-915e-2222643a281e | 8 | public String getPermutation(int n, int k) {
int[] numSet = new int [n];
for (int i=0;i<n;i++){
numSet[i] = i+1;
}
int cur = 1;
while (cur<k) {
int exIndex = n-2;
for (;exIndex>=0;exIndex--){
if (numSet[exIndex+1] >numSet[exIndex])
break;
}
for (int i = n-1;i>exIndex;i--){
if (numSet[i]>numSet[exIndex]) {
numSet[exIndex] += numSet[i];
numSet[i] = numSet[exIndex]- numSet[i];
numSet[exIndex] -= numSet[i];
break;
}
}
int start = exIndex+1, end = n-1;
while (start<end) {
numSet[start] += numSet[end];
numSet[end] = numSet[start]- numSet[end];
numSet[start] -= numSet[end];
start++;end--;
}
cur++;
}
String result = "";
for (int i=0;i<n;i++){
result += numSet[i];
}
return result;
} |
9b0d9b0f-1d36-4c23-9361-cc171bab4ef3 | 1 | public static DataTag getWorldData(int index){
Object obj = read("world/world_"+index);
if(obj == null)
return null;
JSONObject data = (JSONObject) obj;
return new DataTag(data);
} |
6ec4b2ee-ee62-45df-8868-fbe59a0613d0 | 0 | public void setUser(User user) {
this.m_user = user;
} |
1827cc79-b89b-4961-a6c3-ae0122d8199e | 0 | public void setGetAccountRequest(GetAccountRequest getAccountRequest) {
this.getAccountRequest = getAccountRequest;
} |
6985efbb-7f0b-47c9-be34-68c7bcf4ae94 | 3 | @Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof KnowMafiaMessage)) return false;
KnowMafiaMessage that = (KnowMafiaMessage) o;
if (!Arrays.equals(players, that.players)) return false;
return true;
} |
d9667cd2-4ec0-423d-8cdc-c3952a2cd6b5 | 9 | public void setup(Map attributes) {
Map macAttrib = new HashMap();
macAttrib.put(HMac.USE_WITH_PKCS5_V2, Boolean.TRUE);
byte[] s = (byte[]) attributes.get(IPBE.SALT);
if (s == null) {
if (salt == null) {
throw new IllegalArgumentException("no salt specified");
} // Otherwise re-use.
} else {
salt = s;
}
char[] password = (char[]) attributes.get(IPBE.PASSWORD);
if (password != null) {
try {
macAttrib.put(IMac.MAC_KEY_MATERIAL, new String(password).getBytes("UTF-8"));
} catch (UnsupportedEncodingException uee) {
throw new Error(uee.getMessage());
}
} else if (!initialised) {
throw new IllegalArgumentException("no password specified");
} // otherwise re-use previous password.
try {
mac.init(macAttrib);
} catch (Exception x) {
throw new IllegalArgumentException(x.getMessage());
}
Integer ic = (Integer) attributes.get(IPBE.ITERATION_COUNT);
if (ic != null) {
iterationCount = ic.intValue();
}
if (iterationCount <= 0) {
throw new IllegalArgumentException("bad iteration count");
}
count = 0L;
buffer = new byte[mac.macSize()];
try {
fillBlock();
// } catch (Exception x) {
} catch (LimitReachedException x) {
// x.printStackTrace(System.err);
throw new Error(x.getMessage());
}
} |
42009d7d-0582-4eec-a4b0-75f0a86a8bae | 1 | public void updateProfile() {
tUsername.setText(currentProfile.getUsername());
tDisplayName.setText(currentProfile.getDisplayName());
tStartDate.setText(currentProfile.getStartDate().toString());
if (currentProfile.isRightHanded()) tHanded.setText("Right");
else tHanded.setText("Left");
tFavoriteDisc.setText(currentProfile.getFavoriteDiscName());
tFavoriteCourse.setText(currentProfile.getFavoriteCourseName());
tGamesPlayed.setText("" + currentProfile.getGamesPlayed());
tHolesinone.setText("" + currentProfile.getHolesInOne());
tEagles.setText("" + currentProfile.getEagles());
tBirdies.setText("" + currentProfile.getBirdies());
tProfileSummary.setText(currentProfile.getProfileSummary());
System.out.println(currentProfile.getProfileSummary());
} |
74b44022-1d73-40f4-ab9f-8b693a24e96d | 7 | @Override
public void executeMsg(final Environmental myHost, final CMMsg msg)
{
// amazingly important that this happens first!
super.executeMsg(myHost,msg);
if((msg.targetMinor()==CMMsg.TYP_GET)
||(msg.targetMinor()==CMMsg.TYP_GIVE)
||(msg.targetMinor()==CMMsg.TYP_PUT)
||(msg.targetMinor()==CMMsg.TYP_PUSH)
||(msg.targetMinor()==CMMsg.TYP_PULL)
||(msg.sourceMinor()==CMMsg.TYP_THROW)
||(msg.targetMinor()==CMMsg.TYP_DROP))
tryToMoveStuff();
} |
c1cb2978-b54d-489f-9c95-1091b8393d56 | 9 | @SuppressWarnings("RedundantIfStatement")
@Override public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
GitClone gitClone = (GitClone) o;
if (localPath != null ? !localPath.equals(gitClone.localPath) : gitClone.localPath != null) return false;
if (pathToGit != null ? !pathToGit.equals(gitClone.pathToGit) : gitClone.pathToGit != null) return false;
if (repositoryUrl != null ? !repositoryUrl.equals(gitClone.repositoryUrl) : gitClone.repositoryUrl != null)
return false;
return true;
} |
341956d4-3c81-43f6-8b13-900b4451a362 | 3 | public static ArrayList<Order> parseOrdersList(String filePath, String XSDFilePath, Menu menu){
try {
DocumentBuilderFactory documentBuilder = DocumentBuilderFactory.newInstance();
documentBuilder.setIgnoringElementContentWhitespace(true);
Schema schema = SchemaFactory.newInstance(
XMLConstants.W3C_XML_SCHEMA_NS_URI).newSchema(new File(XSDFilePath));
documentBuilder.setSchema(schema);
Document doc = documentBuilder.newDocumentBuilder().parse(filePath);
doc.getDocumentElement().normalize();
ArrayList<Order> orderCollection= new ArrayList<Order>();
NodeList orderList = doc.getElementsByTagName("Order");
for (int j = 0; j < orderList.getLength(); j++) {
Node orderNode = orderList.item(j);
if (orderNode.getNodeType() == Node.ELEMENT_NODE) {
Element orderElement = (Element) orderNode;
Order oneOrder= parseSingleOrderFromOrdersList(orderElement, menu);
orderCollection.add(oneOrder);
}
}
return orderCollection;
}
catch (Exception e) {
System.out.println(e.getMessage());
}
throw (new RuntimeException("error while parsing the orders"));
} |
41ade396-dec5-4986-b00c-2037dd935e26 | 2 | private void selectIMGActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_selectIMGActionPerformed
JFileChooser imgChooser = new JFileChooser();
imgChooser.setFileFilter(new IMGFilter());
imgChooser.setDialogTitle(parser.parse("partitionManager:imgChooserTitle"));
imgChooser.setApproveButtonText(parser.parse("partitionManager:imgChooserApproveButton"));
imgChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
imgChooser.setMultiSelectionEnabled(false);
int result = imgChooser.showOpenDialog(null);
if (result == JOptionPane.OK_OPTION)
jTextField1.setText(imgChooser.getSelectedFile().getAbsolutePath());
else return;
if (debug)
logger.log(Level.DEBUG, "User selected " + jTextField1.getText() + " to flash to " + serialNumber);
}//GEN-LAST:event_selectIMGActionPerformed |
2325cc63-8128-46dc-90b5-c4b9a6ac50f8 | 3 | public void addMoveButton(){
panel=0;
final JButton BackButton = new JButton("назад");
BackButton.setPreferredSize(new Dimension(220,60));
BackButton.setFont(arrFont);
BackButton.setEnabled(false);
final JButton ForwardButton = new JButton("вперёд");
ForwardButton.setPreferredSize(new Dimension(220,60));
ForwardButton.setFont(arrFont);
if(p==0) ForwardButton.setEnabled(false);
BackButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
Layout(--panel);
ForwardButton.setEnabled(true);
if(panel>0) BackButton.setEnabled(true);
else BackButton.setEnabled(false);
}
});
ForwardButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ev) {
Layout(++panel);
BackButton.setEnabled(true);
if(panel==p) ForwardButton.setEnabled(false);
else BackButton.setEnabled(true);
}
});
MovePanel.add(BackButton);
MovePanel.add(ForwardButton);
} |
2c50a7c4-5682-474d-96d2-c10ec0683a52 | 9 | public static long getTokenLongIntegerInternal(char[] buffer, int start, int end, int size) {
{ int length = end - start;
int auxend = end;
long result = 0l;
boolean negativeP = false;
int digit = 0;
if (length < 0) {
length = length + size;
auxend = size;
}
switch (((char) (0x00ff & buffer[start]))) {
case '+':
start = start + 1;
break;
case '-':
start = start + 1;
negativeP = true;
break;
default:
break;
}
loop000 : for (;;) {
while (start < auxend) {
digit = (int) (((char) (0x00ff & buffer[start]))) - (int) '0';
if ((result >= Stella.$GET_TOKEN_LONG_INTEGER_CHECKPOINT$) &&
(((Stella.MOST_POSITIVE_LONG_INTEGER - digit) / (10l)) < result)) {
throw ((StellaException)(StellaException.newStellaException("get-token-long-integer: long-integer overflow").fillInStackTrace()));
}
result = (result * 10) + digit;
start = start + 1;
}
if (auxend == end) {
break loop000;
}
start = 0;
auxend = end;
}
if (negativeP) {
return (0 - result);
}
else {
return (result);
}
}
} |
38d944b1-ffcf-4975-82dd-2bece2b07996 | 3 | public static void beginQuit() {
EnvironmentFrame[] frames = Universe.frames();
for (int i = 0; i < frames.length; i++)
if (!frames[i].close())
return;
//modified by Moti Ben-Ari
if (gui.Main.getDontQuit())
NewAction.closeNew();
else
System.exit(0);
} |
93a4763c-658c-474c-8b5e-3ec33d1319cb | 1 | @Override
public void keyTyped(KeyEvent e) {
if (e.getKeyChar() == '\b') {
// Need to consume backspace here since the action we
// added doesn't seem to supress the built-in backspace code.
e.consume();
}
} |
ab605f26-0d10-4c28-8576-6f2007f2ef64 | 2 | private String hashToString(byte[] hash) {
String result = "";
for (byte b : hash) {
int v = b & 0xFF;
if (v < 16) result += "0";
result += Integer.toString(v, 16).toUpperCase() + " ";
}
return result;
} |
3a0b3b3f-f8d1-4b82-bdc2-c38d43ec1110 | 1 | public void initializeNodes(State[] states) {
myNodes = new Node[states.length];
/** Color all vertices white. */
for (int k = 0; k < states.length; k++) {
Node node = new Node(states[k]);
node.colorWhite();
myNodes[k] = node;
}
} |
847da8df-2cfc-4ea0-a6ee-881a909e2e5e | 2 | public String getOverCurrentMode ()
{
switch (getHubCharacteristics () & 0x0018) {
case 0x00: return "global";
case 0x08: return "per-port";
default: return "none";
}
} |
3a3658e5-d776-4cd8-a85d-e86c988be9d8 | 4 | public static void main(String[] args) {
File file = new File("E:\\blackhand.jpeg");
if (!file.isFile()) {
System.err.print("Error");
}
InputStream stream = null;
try {
stream = new FileInputStream(file);
} catch (FileNotFoundException ex) {
Logger.getLogger(JavaCv.class.getName()).log(Level.SEVERE, null, ex);
}
BufferedImage image = null;
try {
image = ImageIO.read(stream);
} catch (IOException ex) {
Logger.getLogger(JavaCv.class.getName()).log(Level.SEVERE, null, ex);
}
//create the detector
CannyEdgeDetector detector = new CannyEdgeDetector();
//adjust its parameters as desired
detector.setLowThreshold(0.5f);
detector.setHighThreshold(1f);
//apply it to an image
detector.setSourceImage(image);
detector.process();
BufferedImage bufferedImage = detector.getEdgesImage();
try {
// bufferedImage
originalImage = image.getScaledInstance(image.getWidth()/2, image.getHeight()/2, Image.SCALE_DEFAULT);
imageI = bufferedImage.getScaledInstance(image.getWidth()/2, image.getHeight()/2, Image.SCALE_DEFAULT);
JFrame frame = new JFrame();
frame.add(new JavaCv());
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocation(0, 0);
frame.setMinimumSize(new Dimension(image.getWidth()*2, image.getHeight()));
frame.setVisible(true);
} catch (Exception ex) {
Logger.getLogger(JavaCv.class.getName()).log(Level.SEVERE, null, ex);
}
} |
f6da4aae-4561-4e49-9a4a-5ba9c1d9b3b1 | 2 | @EventHandler
public void onPlayerInteractEntity(PlayerInteractEntityEvent event) {
// do not act when disabled TODO, use unregister when available
if ( !this.sheepFeedPlugin.isEnabled() ) {
return;
}
Entity entity = event.getRightClicked();
if (entity.getType() == EntityType.SHEEP) {
this.attemptFeedSheep(event.getPlayer(), (Sheep) entity);
}
} |
1bbae851-b173-404b-9b0f-bb5f955fb1c0 | 2 | @Override
public String execute(SessionRequestContent request) throws ServletLogicException {
String page = (String) request.getSessionAttribute(JSP_PAGE);
List<Country> countryList = (List<Country>) request.getSessionAttribute(JSP_COUNTRY_LIST);
List<City> cityList = (List<City>) request.getSessionAttribute(JSP_CITY_LIST);
Integer idCountry = Integer.decode(request.getParameter(JSP_SELECT_ID));
for (Country c: countryList) {
if (Objects.equals(c.getIdCountry(), idCountry)) {
request.setSessionAttribute(JSP_CURR_CITY_LIST, c.getCityCollection());
request.setAttribute(JSP_CURRENT_COUNTRY, c);
return page;
}
}
request.setSessionAttribute(JSP_CURR_CITY_LIST, cityList);
return page;
} |
8a2f3f6e-7f3f-473b-a69f-19d728d5fb76 | 8 | @EventHandler(priority = EventPriority.HIGH)
public void join(PlayerJoinEvent event) {
if (!plugin.toggle) {
try {
final Player player = event.getPlayer();
plugin.Logger("Player " + event.getPlayer().getTotalExperience() + " XP: " + event.getPlayer().getTotalExperience() + " Level: " + event.getPlayer().getLevel(), "Debug");
// double y = 1.75 * (event.getPlayer().getLevel() + event.getPlayer().getExp()) * (event.getPlayer().getLevel() + event.getPlayer().getExp()) + 4.9997 * (event.getPlayer().getLevel() + event.getPlayer().getExp()) + 0.1327;
// event.getPlayer().setTotalExperience((int) y);
double t = plugin.getLevelXP(player.getLevel()) + (xpShop.nextLevelAt(player.getLevel()) * player.getExp());
player.setTotalExperience((int) t);
plugin.getServer().getScheduler().runTaskLaterAsynchronously(plugin, new Runnable() {
@Override
public void run() {
try {
ArrayList<XPSend> xpSends = plugin.getSendDatabase().getOpenTransactions(player.getName());
for(XPSend send : xpSends) {
plugin.PlayerLogger(player, send.getMessage(), "");
plugin.UpdateXP(player, send.getSendedXP(), "sendxp");
player.saveData();
plugin.getSendDatabase().setStatus(player.getName(), send.getId(), 1);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}, 20);
plugin.Logger("After calculating: Player " + event.getPlayer().getTotalExperience() + " XP: " + event.getPlayer().getTotalExperience() + " Level: " + event.getPlayer().getLevel(), "Debug");
if (!plugin.Blacklistcode.startsWith("1")) {
if (plugin.PermissionsHandler.checkpermissionssilent(event.getPlayer(), "xpShop.admin")) {
if (xpShop.updateaviable) {
plugin.PlayerLogger(event.getPlayer(), "installed xpShop version: " + plugin.Version + ", latest version: " + plugin.newversion, "Warning");
plugin.PlayerLogger(event.getPlayer(), "New xpShop update aviable: type \"/xpShop update\" to install!", "Warning");
if (!plugin.getConfig().getBoolean("installondownload")) {
plugin.PlayerLogger(event.getPlayer(), "Please edit the config.yml if you wish that the plugin updates itself atomatically!", "Warning");
}
}
}
}
} catch (Exception e) {
plugin.report.report(334, "join event failed", e.getMessage(), "xpShopListener", e);
}
}
} |
c94aeda2-9e8c-4a02-a716-a8578af23e74 | 2 | public JSONObject putOpt(String key, Object value) throws JSONException {
if (key != null && value != null) {
this.put(key, value);
}
return this;
} |
2ccb7c43-dd2e-4a4a-adaa-98e2b2d4c436 | 2 | @Override
public int[] getAttributes() {
Random r = new Random();
int[] local = {0, 0, 0, 0, 0, 0};
for (int i = 0; i < 6; i++) {
int[] rolls = {0, 0, 0, 0};
for (int k = 0; k < 4; k++) {
rolls[k] = r.nextInt(6) + 1;
}
Arrays.sort(rolls);
int sum = rolls[1] + rolls[2] + rolls[3];
local[i] = sum;
}
return local;
} |
f3ebdfad-a077-4a5a-b3ca-cae54b85802c | 2 | private <E extends Signable> String post(String apiStr, E object, Function<E, String> fn) throws MailChimpException {
try {
String toPost = fn.apply(sign(object));
final Request request = Request
.Post(mailchimpHost + apiStr)
.addHeader("Content-Type", "application/json")
.body(new StringEntity(toPost, StandardCharsets.UTF_8))
.connectTimeout(connTimeout);
try {
HttpResponse response = request
.execute()
.returnResponse();
String result = EntityUtils.toString(response.getEntity());
logger.debug(result);
return result;
} catch (IOException | RuntimeException e) {
request.abort();
throw logException("post", e);
}
} catch (RuntimeException e) {
throw logException("post", e);
}
} |
05468c7f-ec6b-46d3-9a9b-24799b2f8b8a | 1 | public void showWindow() {
frame = new JFrame("Welcome to YAMG!");
centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout());
image = new ImagePanel();
JPanel bottom = new JPanel();
startButton = new JButton("Start Game");
startButton.addActionListener(new ButtonListener());
startButton.setEnabled(false);
bottom.add(startButton);
exitButton = new JButton("Exit");
exitButton.addActionListener(new ButtonListener());
exitButton.setEnabled(false);
startButton.addKeyListener(new ExitListener());
bottom.add(exitButton);
bottom.add(new JLabel(" Or, press ESC to exit and ENTER to start."));
centerPanel.add(BorderLayout.CENTER, image);
centerPanel.add(BorderLayout.SOUTH, bottom);
frame.getContentPane().add(centerPanel);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setBounds(Helper.getCenteredBounds(890, 550));
frame.setVisible(true);
try {
animate();
} catch (InterruptedException e) {
e.printStackTrace();
}
} |
b6ea7a55-a736-4c31-90b9-3b4b19011d4b | 0 | @Test
public void testtomap() {
Element nodeElement = document.addElement("data");
Student student = new Student(1, "2", "3", "4", "5");
Map<Object, Object> map = javabeanToMap(student);
Map<Object, Object> m = new HashMap<>();
Map<Object, Object> mm = new HashMap<>();
mm.put("mm1", "mm1");
mm.put("mm2", "mm2");
m.put("m1", "m1");
m.put("m2", "m2");
m.put("mm", mm);
map.put("other", m);
System.out.println(map);
String str = mapToXml(map, nodeElement);
System.out.println(str);
} |
bcfa0ada-6f4b-44a8-9d1f-618e5bb6d267 | 8 | @Override
public void onConnectionDataReceived(Connection connection, byte[] data, int length) throws Exception
{
if (!connection.isAdminMode())
{
String datagram = FRAME_START + FRAME_STATUSSUCCESS + (connection.getIdentifier() >= 0? StringUtils.padLeft(Integer.toHexString(connection.getIdentifier()), 4, '0') : "0000") + StringUtils.getHexStringFromByteArray(data, length);
String responseDatagram = getScriptsManager().executeAction("device/" + getApplication().getName() + "/notifyPackage", datagram);
if (responseDatagram.isEmpty())
throw new Exception ("No response for datagram");
if (!responseDatagram.startsWith(FRAME_START))
throw new Exception ("Unrecognized response");
String status = responseDatagram.substring(2, 4);
if (status.equals(FRAME_STATUSSUCCESS))
{
if (connection.getIdentifier() < 0)
connection.setIdentifier(Integer.parseInt(responseDatagram.substring(4, 8), 16));
String responseData = responseDatagram.substring(8);
if (!responseData.isEmpty())
sendPackage(responseData, connection);
}
else if (status.equals(FRAME_STATUSFAILURE))
{
throw new Exception ("Failed processing datagram. Error: " + new String(StringUtils.getByteArrayFromHexString(responseDatagram.substring(4))));
}
}
} |
3c75066b-9053-43b7-87d4-2cd18f54f6cd | 7 | public boolean wordBreak(String s, Set<String> wordDict) {
if (s==null || s.isEmpty())
return false;
if (wordDict == null || wordDict.size()==0)
return false;
for (int i=0; i<s.length(); ++i) {
if (wordDict.contains(s.substring(0, i+1)) && wordBreak(s.substring(i+1), wordDict))
return true;
}
return false;
} |
755af74b-bc9e-4c1a-bb12-439e33014ebb | 3 | public Vector<GameElement> getGameElementByTag(String Tag)
{
Vector<GameElement> Elements = new Vector<GameElement>();
for(GameElement element : GameElements)
{
if(element.getTag() != null && element.getTag().equals(Tag))
{
Elements.add(element);
}
}
return Elements;
} |
fcd61b22-a236-46b1-8080-cf0d3ef2a01c | 9 | @Override
public synchronized void sendData (byte[] foo, int s, int l,
boolean flush) throws IOException
{
// System.out.println("sendData: l="+l+" sendCount="+sendCount+" flush="+flush);
if (foo != null && l <= 0) return;
if (con == null)
{
connect ();
}
if (sendCount <= 0)
{
connect ();
}
int retry = 2;
while (retry > 0)
{
try
{
if (l > 0) out.write (foo, s, l);
sendCount -= l;
// if(flush){
out.close ();
out = null;
try
{
con.connect ();
}
catch (ConnectException e)
{
con.disconnect ();
con = null;
if (foo == null)
{ // data retrieve
connect ();
retry--;
continue;
}
ibdj.connected = false;
return;
}
sessionid = con.getHeaderField ("x-SESSIONID");
// System.out.println("sessionid: "+sessionid);
in = con.getInputStream ();
readData ();
// sendCount=0;
// return;
// }
return;
}
catch (IOException e)
{
connect ();
}
retry--;
}
} |
7cbb7499-75b8-46e3-aa7f-26fc04ff1816 | 5 | private void parseLoadout(JSONObject o) throws ProtocolException {
try {
if(!(o.get("message").equals("loadout"))){
throw new ProtocolException("Expected 'loadout', but got '" + o.get("message") + "' key");
}
if(!Util.validateWeapon(o.getString("primary-weapon"))){
throw new ProtocolException("Invalid primary weapon: '"
+ o.getString("primary-weapon") + "'");
}
if(!Util.validateWeapon(o.getString("secondary-weapon"))){
throw new ProtocolException("Invalid secondary weapon: '"
+ o.getString("secondary-weapon") + "'");
}
if(o.getString("primary-weapon").equals(o.getString("secondary-weapon"))){
throw new ProtocolException("Invalid loadout: Can't have the same weapon twice.");
}
primaryWeapon = o.getString("primary-weapon");
secondaryWeapon = o.getString("secondary-weapon");
Debug.info(username + " selected loadout: " + primaryWeapon + " and "
+ secondaryWeapon + ".");
gotLoadout.set(true);
}
catch (JSONException e){
throw new ProtocolException("Invalid or incomplete packet: " + e.getMessage());
}
} |
745e4304-f905-4b26-9f96-a7d805bd2123 | 4 | private void writeNode(XMLNode node, int tabIndex, FileWriter writer)
throws IOException {
String line = formTabs(tabIndex) + "<" + node.getName();
if (node.getAttributes().size() > 0) {
for (int i = 0; i < node.getAttributes().size(); i++) {
line += " " + formAttribute(node.getAttributes().get(i));
}
}
if (node.getChilds().size() == 0) {
line += "/>";
writer.write(line + "\n");
} else {
line += ">";
writer.write(line + "\n");
for (XMLNode child : node.getChilds()) {
writeNode(child, tabIndex + 1, writer);
}
writer.write(formTabs(tabIndex) + "</" + node.getName() + ">\n");
}
} |
6dd3a2d6-dac9-44c5-a135-c156a339c4d2 | 4 | @SuppressWarnings(value="unchecked")
public void put(int field$, java.lang.Object value$) {
switch (field$) {
case 0: names = (java.util.Map<java.lang.CharSequence,java.lang.CharSequence>)value$; break;
case 1: name = (java.lang.CharSequence)value$; break;
case 2: favorite_number = (java.lang.Integer)value$; break;
case 3: favorite_color = (java.lang.CharSequence)value$; break;
default: throw new org.apache.avro.AvroRuntimeException("Bad index");
}
} |
328ce178-17e0-49e6-888e-607eeb26b919 | 7 | private JSONWriter append(String s) throws JSONException {
if (s == null) {
throw new JSONException("Null pointer");
}
if (this.mode == 'o' || this.mode == 'a') {
try {
if (this.comma && this.mode == 'a') {
this.writer.write(',');
}
this.writer.write(s);
} catch (IOException e) {
throw new JSONException(e);
}
if (this.mode == 'o') {
this.mode = 'k';
}
this.comma = true;
return this;
}
throw new JSONException("Value out of sequence.");
} |
694c63e7-d8c3-4565-8435-bc574c18fb06 | 8 | private void juliaMapPolar(int image_size) {
double size = fractal.getSize();
double xcenter = fractal.getXCenter();
double ycenter = fractal.getYCenter();
double start;
double center = Math.log(size);
int pixel_percent = image_size * image_size / 100;
double f, sf, cf, r;
double muly = (2 * circle_period * Math.PI) / (TOx - FROMx);
double mulx = muly * height_ratio;
start = center - mulx * (TOx - FROMx) / 2.0;
for(int y = FROMy, y1 = 0; y < TOy; y++, y1++) {
f = y1 * muly;
sf = Math.sin(f);
cf = Math.cos(f);
for(int x = FROMx, x1 = 0, loc = y * image_size + x; x < TOx; x++, loc++, x1++) {
r = Math.exp(x1 * mulx + start);
image_iterations[loc] = fractal.calculateJulia(new Complex(xcenter + r * cf, ycenter + r * sf));
rgbs[loc] = getColor(image_iterations[loc]);
drawing_done++;
}
if(drawing_done / pixel_percent >= 1) {
update(drawing_done);
drawing_done = 0;
}
}
if(bump_map || fake_de || rainbow_palette) {
try {
post_processing_sync.await();
}
catch(InterruptedException ex) {
}
catch(BrokenBarrierException ex) {
}
applyPostProcessing(image_size);
}
} |
6437d911-a910-4e96-b731-c112ebfc205d | 9 | public void runGameTimedSpeedOptimised(Controller<MOVE> pacManController,Controller<EnumMap<GHOST,MOVE>> ghostController,boolean fixedTime,boolean visual)
{
Game game=new Game(0);
GameView gv=null;
if(visual)
gv=new GameView(game).showGame();
if(pacManController instanceof HumanController)
gv.getFrame().addKeyListener(((HumanController)pacManController).getKeyboardInput());
new Thread(pacManController).start();
new Thread(ghostController).start();
while(!game.gameOver())
{
pacManController.update(game.copy(),System.currentTimeMillis()+DELAY);
ghostController.update(game.copy(),System.currentTimeMillis()+DELAY);
try
{
int waited=DELAY/INTERVAL_WAIT;
for(int j=0;j<DELAY/INTERVAL_WAIT;j++)
{
Thread.sleep(INTERVAL_WAIT);
if(pacManController.hasComputed() && ghostController.hasComputed())
{
waited=j;
break;
}
}
if(fixedTime)
Thread.sleep(((DELAY/INTERVAL_WAIT)-waited)*INTERVAL_WAIT);
game.advanceGame(pacManController.getMove(),ghostController.getMove());
}
catch(InterruptedException e)
{
e.printStackTrace();
}
if(visual)
gv.repaint();
}
pacManController.terminate();
ghostController.terminate();
} |
47b5dad5-32e2-4d63-990a-5c6a2951de31 | 8 | protected void print(Data data, int indentLevel) {
StringBuffer text = new StringBuffer(80);
for(int i = 0; i < indentLevel; ++i) {
text.append(indentationPrefix);
}
text.append(data.getName()).append(": ");
if(data.isPlain()) {
try {
Data.TextValue textValue = data.asTextValue();
String value = textValue.getValueText();
int kommaPosition = value.lastIndexOf(',');
if(kommaPosition < 0) {
kommaPosition = value.length();
}
int fillCount = valuePosition - text.length() - kommaPosition;
while(fillCount-- > 0) {
text.append(" ");
}
text.append(value).append(" ");
String suffix = textValue.getSuffixText();
if(!suffix.equals("")) {
fillCount = suffixPosition - text.length();
while(fillCount-- > 0) {
text.append(" ");
}
text.append(suffix);
}
getProtocolFileWriter().println(text.toString());
}
catch(Exception e) {
debug.error(
text.append("<<").append(e.getMessage())
.append(">>").toString()
);
}
}
else {
getProtocolFileWriter().println(text.toString());
Iterator i = data.iterator();
++indentLevel;
while(i.hasNext()) print((Data)i.next(), indentLevel);
}
} |
7663f029-bbaa-4c56-b0a8-a2113977fde3 | 0 | public static int randRange(int min, int max){
Random rn = new Random();
int range = max - min + 1;
int randomNum = rn.nextInt(range) + min;
return randomNum;
} |
1442d2e4-8eea-4496-b119-fa9a50b64904 | 6 | public static int loadTexture(BufferedImage image, boolean linear, boolean flip){
int[] pixels = new int[image.getWidth() * image.getHeight()];
image.getRGB(0, 0, image.getWidth(), image.getHeight(), pixels, 0, image.getWidth());
ByteBuffer buffer = BufferUtils.createByteBuffer(image.getWidth() * image.getHeight() * BYTES_PER_PIXEL);
// Iterate through each pixel of the BufferedImage, place the R, G, B and A component for each pixel into the ByteBuffer
if(!flip){
for (int y = 0; y < image.getHeight(); y++) {
for (int x = 0; x < image.getWidth(); x++) {
int pixel = pixels[y * image.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF)); // Blue component
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component.
}
}
}else{
for (int y = image.getHeight()-1; y >= 0; y--) {
for (int x = 0; x < image.getWidth(); x++) {
int pixel = pixels[y * image.getWidth() + x];
buffer.put((byte) ((pixel >> 16) & 0xFF)); // Red component
buffer.put((byte) ((pixel >> 8) & 0xFF)); // Green component
buffer.put((byte) (pixel & 0xFF)); // Blue component
buffer.put((byte) ((pixel >> 24) & 0xFF)); // Alpha component.
}
}
}
// Buffer must be flipped:
buffer.flip();
// You now have a ByteBuffer filled with the color data of each pixel.
// Now just create a texture ID and bind it. Then you can load it using
// whatever OpenGL method you want, for example:
int textureID = glGenTextures(); //Generate texture ID
glBindTexture(GL_TEXTURE_2D, textureID); //Bind texture ID
//Setup wrap mode
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL12.GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL12.GL_CLAMP_TO_EDGE);
//Setup texture scaling filtering - keep image exactly as imported using GL_NEAREST:
if(linear){
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}else{
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
}
//Send texel data to OpenGL
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, image.getWidth(), image.getHeight(), 0, GL_RGBA, GL_UNSIGNED_BYTE, buffer);
//Return the texture ID so we can bind it later again
return textureID;
} |
c1623ca8-93f6-4c8c-b785-c583078f8283 | 3 | private char nextSkippingWhitespace() throws IOException {
for (;;) {
char c = next();
if (c == 0 || c > ' ') {
return c;
}
}
} |
9520023e-3382-4df2-961b-e4edf1dbbe36 | 4 | @Test
public void testSetListenThreadServerOnSamePort() {
LOGGER.log(Level.INFO, "----- STARTING TEST testSetListenThreadServerOnSamePort -----");
boolean flag1 = false;
boolean flag2 = false;
if (server1.getState() == Server.LISTEN) {
flag1 = true;
}
if (flag1) {
try {
server1.setListenThread();
} catch (IOException | ServerSocketCloseException | TimeoutException e) {
exception = true;
}
if (server1.getState() == Server.LISTEN) {
flag2 = true;
}
}
Assert.assertFalse(exception, "Exception found");
Assert.assertTrue(flag2, "Server's state has not been set as listen Server. listen_thread may have not been created correctly. Server state is " + Integer.toString(server2.getState()));
LOGGER.log(Level.INFO, "----- TEST testSetListenThreadServerOnSamePort COMPLETED -----");
} |
ea01d895-b840-4116-9cc5-a78070639d3f | 0 | public boolean removeNode(Root node) {
return branchs.remove(node);
} |
d0b30b4d-542a-42ec-9a71-16eccaa1c41c | 7 | private void executeReadWrite(final long count, int keyLen, int valueLen) throws IOException {
final int defaultKeyLen = 8;
final int defaultValueLen = 32;
CacheConfig config = new CacheConfig();
config.setStorageMode(storageMode);
cache = new BigCache<String>(TEST_DIR, config);
List<String> keys = new ArrayList<String>();
String key = "";
String value = "";
if (keyLen > 0) {
key = TestUtil.randomString(keyLen);
} else {
key = TestUtil.randomString(defaultKeyLen);
}
if (valueLen > 0) {
value = TestUtil.randomString(valueLen);
} else {
value = TestUtil.randomString(defaultValueLen);
}
for (int i = 0; i < count; i++) {
cache.put(key + i, TestUtil.getBytes(value + i));
keys.add(key + i);
}
assertEquals(cache.count(), count);
for (String k : keys) {
String v = new String(cache.get(k));
String index = k.substring(keyLen > 0 ? keyLen : 8);
assertEquals(value + index, v);
}
for (String k : keys) {
cache.delete(k);
}
for (String k : keys) {
assertNull(cache.get(k));
}
} |
4b83546b-055a-435f-a16c-fcf862118ff8 | 6 | synchronized public Class toClass() throws ClassNotFoundException, UtilEvalError {
if (asClass != null)
return asClass;
reset();
// "var" means untyped, return null class
if (evalName.equals("var"))
return asClass = null;
/* Try straightforward class name first */
Class clas = namespace.getClass(evalName);
if (clas == null) {
/*
* Try toObject() which knows how to work through inner classes and
* see what we end up with
*/
Object obj = null;
try {
// Null interpreter and callstack references.
// class only resolution should not require them.
obj = toObject(null, null, true);
} catch (UtilEvalError e) {
}
; // couldn't resolve it
if (obj instanceof ClassIdentifier)
clas = ((ClassIdentifier) obj).getTargetClass();
}
if (clas == null)
throw new ClassNotFoundException("Class: " + value + " not found in namespace");
asClass = clas;
return asClass;
} |
425b1084-4d0e-4ec9-bf12-a1167782346d | 6 | private static Event nextEvent() {
Event e = null;
if (Keyboard.next()) {
if (Keyboard.getEventKeyState()) {
e = new Event(EventType.KEY_PRESSED, Keyboard.getEventKey());
} else {
e = new Event(EventType.KEY_RELEASED, Keyboard.getEventKey());
}
}
if (Mouse.next()) {
if (Mouse.getEventDX() != 0 || Mouse.getEventDY() != 0)
e = new Event(EventType.MOUSE_MOVE, 0);
else if (Mouse.getEventButtonState())
e = new Event(EventType.MOUSE_PRESSED, Mouse.getEventButton());
else
e = new Event(EventType.MOUSE_RELEASED, Mouse.getEventButton());
}
return e;
} |
57c1d3b9-618e-4b42-856d-74099c74d669 | 1 | Map<Person, List<Score>> removeFromTable(Map<Person, List<Score>> table, Person p){
table.remove(p);
table.values()
.forEach(list -> list.removeIf(it -> it.self.equals(p) || it.target.equals(p)));
return table;
} |
00faa96f-b1e6-4fa6-a585-695b4ddcdf98 | 5 | @Override
public void processKeyboard()
{
if(Keyboard.isKeyDown(Keyboard.KEY_1))
{
map_.setTemperatureAlgo(temperature_algo_noise_);
map_.generate();
}
else if(Keyboard.isKeyDown(Keyboard.KEY_2))
{
map_.setTemperatureAlgo(temperature_algo_linear_);
map_.generate();
}
else if(Keyboard.isKeyDown(Keyboard.KEY_3))
{
map_.setTemperatureAlgo(temperature_algo_sum0_);
map_.generate();
}
else if(Keyboard.isKeyDown(Keyboard.KEY_4))
{
map_.setTemperatureAlgo(temperature_algo_radial_);
map_.generate();
}
else if(Keyboard.isKeyDown(Keyboard.KEY_5))
{
map_.setTemperatureAlgo(temperature_algo_sum1_);
map_.generate();
}
} |
3f576e60-37c0-4c19-a6f5-0fcf1011538f | 7 | public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
} |
b95e3ec3-8602-4be6-b6fd-7a3161e8221b | 4 | public boolean httpGet(String url, String queryString,
QAsyncHandler callback, Object cookie) {
if (url == null || url.equals("")) {
return false;
}
if (queryString != null && !queryString.equals("")) {
url += "?" + queryString;
}
GetMethod httpGet = new GetMethod(url);
httpGet.getParams().setParameter("http.socket.timeout",
new Integer(CONNECTION_TIMEOUT));
mThreadPool.submit(new AsyncThread(httpGet, callback, cookie));
return true;
} |
f1e62eac-c684-4e9c-9ada-793b0ace5664 | 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(Gerais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Gerais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Gerais.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Gerais.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 Gerais().setVisible(true);
}
});
} |
c494d662-fe16-41b7-9366-60001f8af449 | 3 | @Override
public String execute() throws Exception {
try {
Map session = ActionContext.getContext().getSession();
setUser((User) session.get("User"));
pid = (Long) Long.parseLong(publishid);
Publish sitepublish;
sitepublish = new Publish(getUser(), siteurl, catgry);
sitepublish.setPublishId(pid);
sitepublish.setBgColor(bgcolor);
sitepublish.setTextColor(txtcolor);
sitepublish.setDescription(desc);
sitepublish.setSiteName(sitename);
myDao.getDbsession().update(sitepublish);
sitelist = (List<Publish>) myDao.getDbsession().createQuery("from Publish").list();
Criteria crit1 = myDao.getDbsession().createCriteria(Publish.class);
crit1.add(Restrictions.like("user", getUser()));
crit1.setMaxResults(20);
sitelist = (List<Publish>) crit1.list();
addActionMessage("Site " + sitename + " Information Successfully Updated");
return "success";
} catch (HibernateException e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
} catch (NullPointerException ne) {
addActionError("Server Error Please Recheck All Fields ");
ne.printStackTrace();
return "error";
} catch (Exception e) {
addActionError("Server Error Please Recheck All Fields ");
e.printStackTrace();
return "error";
}
} |
be6b9a01-a6dd-486b-9c51-bf6a8a90b61c | 0 | public void setRemotePort(int remotePort) {
this.remotePort = remotePort;
} |
d575302f-651c-429a-8f00-b32680d245ed | 9 | @Override
public boolean equals(Object o) {
if(this == o) return true;
if(o == null || getClass() != o.getClass()) return false;
Rendering rendering = (Rendering) o;
if(image.equals(rendering.image)) return true;
if(!(image.getWidth() == rendering.image.getWidth())) return false;
if(!(image.getHeight() == rendering.image.getHeight())) return false;
for(int x = 0; x < image.getWidth(); x++) {
for(int y = 0; y < image.getHeight(); y++) {
if(image.getRGB(x, y) != rendering.image.getRGB(x, y)) return false;
}
}
return true;
} |
d75d03e4-9fff-42ac-9853-1996d1f6747c | 8 | public void act()
{
setImage(grenade);
if (distance <= 0)
{
if (distance == 0)
{
dealtDamage(this.x, this.y, 200, 200, 1, 0, 10.0, 200);
Greenfoot.playSound("Sound//Bond//Grenade.mp3");
}
y = 400;
setRotation(0);
explosiveFrame++;
this.setLocation(this.x, this.y);
grenade = new GreenfootImage ("Ranged//explosive//explosive00"+explosiveFrame+".png");
if (explosiveFrame == 26)
{
getWorld().removeObject(this);
}
}
else
{
this.setLocation(this.x, this.y);
if (this.direction == true)
{
this.x = this.x + 7;
}
else
{
this.x = this.x - 7;
}
if (this.y >= 470)
{
distance = distance/2;
}
if (this.y <= 470 - distance)
{
moveUp = false;
}
else if (this.y >= 470)
{
moveUp = true;
}
if (moveUp)
{
this.y = this.y - 3;
}
else
{
this.y = this.y + 3;
}
}
} |
1aa717cb-1fcb-4cb3-9678-3f917d6a4670 | 0 | public String getCategoryName() {
return categoryName;
} |
af6b18bc-6711-4262-be38-0f95aa591e9d | 6 | public static boolean deleteLocalPath(String path)
{
if (path == null || path.equals(""))
{
return false;
}
java.io.File f = new java.io.File(path);
if (!f.exists())
{
System.out.println("Local directory is not exist:" + path);
return true;
}
String[] tmp = f.list();
for (int i = 0; tmp != null && i < tmp.length; i++)
{
deleteLocalPath(path + "/" + tmp[i]);
}
if (f.delete())
{
System.out.println("delete Local directory success:" + path);
return true;
}
else
{
System.out.println("delete Local directory fail:" + path);
return false;
}
} |
a1293f78-9e8c-4325-a0fa-ca5f683377aa | 0 | private void initialize() {
new JFrame();
this.setResizable(false);
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
this.setSize(WINDOW_SIZE);
this.setLocation(screenSize.width/2-getWidth()/2, screenSize.height/2-getHeight()/2);
this.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
this.getContentPane().setLayout(null);
dataList = Main.getStructureBase();
controlsStructLength();
controlsDataParam();
initTable();
initButtons();
initPopupMenu();
controlsKitParam();
} |
3d80eee9-4781-4e70-9903-d2bef246e00b | 2 | private void crossOver(Chromo<T> offspring1, Chromo<T> offspring2){
T tmp;
List<T> genes1 = offspring1.getGenes();
List<T> genes2 = offspring2.getGenes();
if (rand.nextDouble() < CROSSOVER_RATE){
int position = (rand.nextInt(genes1.size()));
for (int i=position; i<genes1.size(); i++){
tmp = genes1.get(i);
genes1.set(i, genes2.get(i));
genes2.set(i, tmp);
}
}
offspring1.setGenes(genes1);
offspring2.setGenes(genes2);
} |
01e6aa34-d846-4b39-b9b8-dd2c64911cf9 | 7 | static int rotatedBinarySearch(Integer array[], int key, int start, int end)
{
if (start > end)
return -1;
int middle = start+(end-start)/2;
// ****IMPORTANT
if (array[middle] == key)
return middle;
// lower half is sorted
if (array[start] < array[middle]){ // ****IMPORTANT
if (key >= array[start] && key < array[middle]) {
//key in lower sorted half - use normal BS
return binarySearch(array, key, start, middle - 1);
}else {
//System.out.println("key: "+key +" start: " + start + " middle: " + middle + " end: " + end+ " start: " +array[start] + " middle: " + array[middle] + " end: " + array[end]);
//key in unsorted upper half
return rotatedBinarySearch(array, key, middle + 1, end);
}
}
// upper is sorted
else {
if (key > array[middle] && key <= array[end]) {
//key in upper sorted half - use normal BS
return binarySearch(array, key, middle + 1, end);
}else {
//System.out.println("key: "+key +" start: " + start + " middle: " + middle + " end: " + end+ " start: " +array[start] + " middle: " + array[middle] + " end: " + array[end]);
//key in unsorted lower half
return rotatedBinarySearch(array, key, start, middle - 1);
}
}
} |
402ed7a7-9c34-476e-97ea-58050136036b | 2 | private boolean goToX(int xDestination) {
if (x != xDestination) {
if (!isOnPath()) {
goToPath();
return false;
} else {
return stepInDirectionOfX(xDestination);
}
} else {
return true;
}
} |
4d163726-b7c1-4125-aa2a-28d919fe1567 | 6 | public static Set<IvyPackageClasspathEntry> build(String basepath, String var, String ivyUserDir, ResolveReport report) {
Set<IvyPackageClasspathEntry> result = new HashSet<IvyPackageClasspathEntry>();
HashMap<IvyPackageKey, IvyPackage> packages = new HashMap<IvyPackageKey,IvyPackage>();
for(ArtifactDownloadReport r : report.getAllArtifactsReports()) {
Artifact a = r.getArtifact();
String name = a.getName();
String organisation = a.getAttribute(ATTR_ORGANISATION);
if( TypeUtils.jar(a) ) {
IvyPackageKey packageKey = new IvyPackageKey(organisation,name);
IvyPackage ivyPackage = get(packages,packageKey);
ivyPackage.jar = r;
result.add(new IvyPackageClasspathEntry(basepath, var, ivyUserDir, ivyPackage));
} else if( TypeUtils.source(a) ) {
if(name.endsWith("-sources"))
name = name.substring(0,name.length()-"-sources".length());
IvyPackageKey packageKey = new IvyPackageKey(organisation,name);
get(packages,packageKey).sources=r;
} else if( TypeUtils.javadoc(a) ) {
if(name.endsWith("-javadoc"))
name = name.substring(0,name.length()-"-javadoc".length());
IvyPackageKey packageKey = new IvyPackageKey(organisation,name);
get(packages,packageKey).javadoc=r;
}
}
return result;
} |
6dab5445-34d9-49d0-ac62-9efb8f0dbae2 | 0 | @Override
protected boolean removeEldestEntry(Map.Entry<CacheKey, Object> eldest) {
return size() > CACHE_SIZE;
} |
e5d08f39-c654-4278-9f2f-ccb51a52485c | 7 | public static void main(String[] args) {
List<Integer> abundant = new ArrayList<Integer>();
for(int i = 1; i < limit; i++) {
if(getSumOfProperDivisors(i) > i)
abundant.add(i);
}
boolean[] canBeAbundantSum = new boolean[limit + 1];
for(int i = 0; i < abundant.size(); i++)
for(int j = 0; j < abundant.size(); j++)
if(abundant.get(i) + abundant.get(j) <= limit)
canBeAbundantSum[abundant.get(i) + abundant.get(j)] = true;
int sum = 0;
for(int i = 0; i < canBeAbundantSum.length; i++)
if(!canBeAbundantSum[i])
sum += i;
System.out.println(sum);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.