method_id
stringlengths 36
36
| cyclomatic_complexity
int32 0
9
| method_text
stringlengths 14
410k
|
---|---|---|
f9244b32-c32b-4beb-bb17-8b1b3f791e8f | 0 | public int getMsgType() {
return MsgType;
} |
2eca7d49-a0ee-43dc-8993-19fa0bca5566 | 5 | private void FireSale ( int j, Housedata tAISYOUHOUSE, List<HPAdata> iFurnitureList, HPAdata taisyouHPA, int k, int l, ReadFile RF ) { //ϋvx̒Ⴂ𓊂肵܂
if ( j >= 2 ) { //_uĂƂ̂ݓ\bh
int Dur = Integer.MAX_VALUE; //ϋvxp̃L[
int II = Integer.MAX_VALUE; //Lpi
for ( int i = 0; i < getdoubleList().size(); i++ ) {
if ( getdoubleList().get(i).getDurability()< Dur ) {
Dur = getdoubleList().get(i).getDurability();
II = i; //wϋvxႢقioĂ
}
}
int ID = getdoubleList().get(II).getID(); //̂イǂ̒Ⴂ̂hcĂ
for ( int i = 0; i < iFurnitureList.size(); i++ ) {
if ( ID == iFurnitureList.get(i).getID() ) { //Ȃhc̉Ɠdセ̉Ɠd͓ɏ
//System.out.println(Dur+ " + " + II + " + " + j + " + " + ID + " " + tAISYOUHOUSE.getName() );
int Val = (int) (iFurnitureList.get(i).getTermValue() * 0.3); //1œ
RF.getHouseList ().get ( k ).getFurnitureList ().get ( l ).setTermValue( Val );
}
}
}
} |
f75ea426-f224-4290-8ac1-c0e3b07dfe4a | 3 | public static void writeString(byte[] data, int offset, int length, String string) {
if(data.length < offset + length) {
throw new IllegalArgumentException("Not enough space for writing a String at " + offset + " of length " + length);
}
for(int i = 0; i < length; i++) {
if(i >= string.length()) {
data[offset + i] = 0;
} else {
data[offset + i] = (byte) (string.charAt(i) & 0xFF);
}
}
} |
72096dfb-a918-4151-b60f-2686501a5fdd | 4 | public State evalGame() {
// don't show anything, just return the final state
// shameless code copying...
// Actually play the game
// as long as there are empty squares
while (s.getnEmpty() > 0) {
Move m;
// ask the right player to make a move
if (s.whoseTurn().equals("red"))
m = red.chooseMove(s);
else
m = blue.chooseMove(s);
// fail miserably if the move is illegal or if the player fails te
// produce a move
if (m == null || !s.legalMove(m)) {
System.err.println(s.whoseTurn()
+ " did not produce a legal move. Ending game.");
return s;
}
// apply move
s.applyMove(m);
}
return s;
} |
6282c7c3-6f8f-4ce6-b4b2-1441533d9ca8 | 1 | public void increment() {
count++;
if (count > maxPublCount)
maxPublCount = count;
} |
b40e8d3b-a285-4c1c-923f-2bfa8fdc10a1 | 6 | public void nodeLeft(String gs)
{
maintenance = true;
System.out.println("Node down! Overlay repair in progres..");
/*String tmp = this.getUrl() + " Known clusters: ";
for (String s : resourceManagerLoad.keySet())
{
tmp += s + ", ";
}
logger.info(tmp);*/
for (String s : resourceManagerLoad.keySet())
{
System.out.println("Informing " + s + ".");
ControlMessage cMessage = new ControlMessage(ControlMessageType.GSDown);
cMessage.setUrl(this.getUrl());
cMessage.setSLoad(gs);
sendMessage(cMessage, s);
//socket.sendMessage(cMessage, "localsocket://" + s);
}
if (gs.equals(downstream_neighbour) || gs.equals(upstream_neighbour))
{
if (gs.equals(downstream_neighbour))
{
ControlMessage cMessage = new ControlMessage(ControlMessageType.CrashedGS);
cMessage.setUrl(this.getUrl());
cMessage.setSLoad(gs);
sendMessage(cMessage, upstream_neighbour);
//socket.sendMessage(cMessage, "localsocket://" + upstream_neighbour);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ControlMessage cMessage2 = new ControlMessage(ControlMessageType.NeighborRequest);
cMessage2.setUrl(this.getUrl());
cMessage2.setLoad(this.getUrl());
cMessage2.setSLoad(gs);
sendMessage(cMessage2, upstream_neighbour);
//socket.sendMessage(cMessage2, "localsocket://" + upstream_neighbour);
}
else
{
ControlMessage cMessage = new ControlMessage(ControlMessageType.CrashedGS);
cMessage.setUrl(this.getUrl());
cMessage.setSLoad(gs);
sendMessage(cMessage, downstream_neighbour);
//socket.sendMessage(cMessage, "localsocket://" + downstream_neighbour);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
ControlMessage cMessage2 = new ControlMessage(ControlMessageType.NeighborRequest);
cMessage2.setUrl(this.getUrl());
cMessage2.setLoad(this.getUrl());
cMessage2.setSLoad(gs);
sendMessage(cMessage2, downstream_neighbour);
//socket.sendMessage(cMessage2, "localsocket://" + downstream_neighbour);
}
}
else
{
ControlMessage cMessage = new ControlMessage(ControlMessageType.CrashedGS);
cMessage.setUrl(this.getUrl());
cMessage.setSLoad(gs);
sendMessage(cMessage, upstream_neighbour);
//socket.sendMessage(cMessage, "localsocket://" + upstream_neighbour);
ControlMessage cMessage2 = new ControlMessage(ControlMessageType.CrashedGS);
cMessage2.setUrl(this.getUrl());
cMessage2.setSLoad(gs);
sendMessage(cMessage2, downstream_neighbour);
//socket.sendMessage(cMessage2, "localsocket://" + downstream_neighbour);
}
} |
5204cff8-4730-4c62-89d7-9a9a20b6f325 | 2 | public static Date DateParse(String str){
if(MyStringUtil.isBlank(str)){
return null;
}
try{
return format.parse(str);
}catch(Exception e){
e.printStackTrace();
}
return null;
} |
7b2d135c-2734-447b-92c7-29a2b0511ece | 7 | public SeleksiPegawaiView(SingleFrameApplication app) {
super(app);
initComponents();
// status bar initialization - message timeout, idle icon and busy animation, etc
ResourceMap resourceMap = getResourceMap();
int messageTimeout = resourceMap.getInteger("StatusBar.messageTimeout");
messageTimer = new Timer(messageTimeout, new ActionListener() {
public void actionPerformed(ActionEvent e) {
statusMessageLabel.setText("");
}
});
messageTimer.setRepeats(false);
int busyAnimationRate = resourceMap.getInteger("StatusBar.busyAnimationRate");
for (int i = 0; i < busyIcons.length; i++) {
busyIcons[i] = resourceMap.getIcon("StatusBar.busyIcons[" + i + "]");
}
busyIconTimer = new Timer(busyAnimationRate, new ActionListener() {
public void actionPerformed(ActionEvent e) {
busyIconIndex = (busyIconIndex + 1) % busyIcons.length;
statusAnimationLabel.setIcon(busyIcons[busyIconIndex]);
}
});
idleIcon = resourceMap.getIcon("StatusBar.idleIcon");
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
// connecting action tasks to status bar via TaskMonitor
TaskMonitor taskMonitor = new TaskMonitor(getApplication().getContext());
taskMonitor.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
public void propertyChange(java.beans.PropertyChangeEvent evt) {
String propertyName = evt.getPropertyName();
if ("started".equals(propertyName)) {
if (!busyIconTimer.isRunning()) {
statusAnimationLabel.setIcon(busyIcons[0]);
busyIconIndex = 0;
busyIconTimer.start();
}
progressBar.setVisible(true);
progressBar.setIndeterminate(true);
} else if ("done".equals(propertyName)) {
busyIconTimer.stop();
statusAnimationLabel.setIcon(idleIcon);
progressBar.setVisible(false);
progressBar.setValue(0);
} else if ("message".equals(propertyName)) {
String text = (String)(evt.getNewValue());
statusMessageLabel.setText((text == null) ? "" : text);
messageTimer.restart();
} else if ("progress".equals(propertyName)) {
int value = (Integer)(evt.getNewValue());
progressBar.setVisible(true);
progressBar.setIndeterminate(false);
progressBar.setValue(value);
}
}
});
} |
0ae5233b-235d-4c26-b940-4ca8e0df848d | 8 | @Override
public void actionPerformed(ActionEvent e) {
switch(e.getActionCommand()){
case RUN:
Application.mediator.parseLSA();
LSAmatrix m = Application.mediator.matrix;
Application.mediator.writeInfo(m.toString());
break;
case VALIDATE:
Application.mediator.parseLSA();
m = Application.mediator.matrix;
String messages = m.validateMatrix();
if(messages.equals("")){
Application.mediator.writeInfo("Matrix is validated\n");
}else{
Application.mediator.writeInfo("Some problems with vertexes: \n"
+ messages );
}
Application.mediator.writeInfo(m.showRoads());
break;
case SYNTHESIZE:
Application.mediator.parseLSA();
Application.mediator.synthesizer.findAllConnetions();
Application.mediator.writeInfo(Application.mediator.automatonTable.getConnectionsInfo());
break;
case ADJACENT:
Map<Integer,ZState> states = ConnectionAnalyzer.createStates(Application.mediator.automatonTable.connections);
try {
ConnectionAnalyzer.encode(states);
} catch (Exception ex) {
Logger.getLogger(RunMenuListener.class.getName()).log(Level.SEVERE, null, ex);
Application.mediator.writeInfo(ex.getMessage());
}
AutomatonTable table = ConnectionAnalyzer.getConnections(states);
Application.mediator.automatonTable.connections = table.connections;
Application.mediator.automatonTable.ids = table.ids;
Application.mediator.automatonTable.codes = table.codes;
Application.mediator.automatonFrame.panel.initPanels();
Application.mediator.showConnections();
break;
case CODE_TRIGERS:
Application.mediator.automatonTable.codeTrigrers();
Application.mediator.tableFrame = null;
Application.mediator.writeInfo("Trigers encoded");
break;
case MINIMIZE:
Minimizator minimizator = new Minimizator(Application.mediator.automatonTable);
Application.mediator.writeInfo(Minimizator.showTable(minimizator.ids, minimizator.signals));
minimizator.generateFunctions();
Application.mediator.writeInfo("Initial version:");
Application.mediator.writeInfo(Minimizator.showFunctions(minimizator.functions, minimizator.ids));
minimizator.minimize();
Application.mediator.writeInfo("Minimized version:");
Application.mediator.writeInfo(Minimizator.showFunctions(minimizator.minimize_functions, minimizator.ids));
Application.mediator.writeInfo("Result:");
Application.mediator.writeInfo(minimizator.analyzeMinimization());
break;
}
} |
f8dc9d85-ab64-444b-9bc1-b99ee017190b | 6 | public void setExit(String direction, Room neighbor, boolean blockedUntilOpened)
{
if(direction == "north")
northBlocked = blockedUntilOpened;
if(direction == "south")
southBlocked = blockedUntilOpened;
if(direction == "east")
eastBlocked = blockedUntilOpened;
if(direction == "west")
westBlocked = blockedUntilOpened;
if(direction == "up")
upBlocked = blockedUntilOpened;
if(direction == "down")
downBlocked = blockedUntilOpened;
super.setExit(direction, neighbor);
} |
0b2a96c6-ced5-4667-932a-573baac3d732 | 7 | void parseLoopParameters(String[] fields) throws Exception {
fieldCount = 0;
for (int i = 0; i < fields.length; i++)
propertyReferenced[i] = false;
propertyCount = fields.length;
while (true) {
String str = tokenizer.peekToken();
if (str == null) {
fieldCount = 0;
break;
}
if (str.charAt(0) != '_')
break;
tokenizer.getTokenPeeked();
fieldTypes[fieldCount] = NONE;
for (int i = fields.length; --i >= 0;)
if (isMatch(str, fields[i])) {
fieldTypes[fieldCount] = i;
propertyReferenced[i] = true;
break;
}
fieldCount++;
}
if (fieldCount > 0)
loopData = new String[fieldCount];
} |
af103244-1a2e-42ef-ace9-8edff99a93e5 | 5 | public void paste(World world, int x, int y, int z)
{
if(valid)
{
for(int xPos = x; xPos < x+width; x++)
{
for(int zPos = z; zPos < z+length; z++)
{
for(int yPos = y; yPos < y+height; yPos++)
{
populator.setBlockWithData(world, xPos, yPos, zPos, materialList[structure[x][y][z]], materialListData[structure[x][y][z]]);
}
}
}
int size = blockStates.size();
for(int a = 0; a < size; a++)
{
TileEntity t = blockStates.get(a);
NBTTagCompound data = new NBTTagCompound();
t.b(data);
t = TileEntity.c(data);
t.a(new BlockPosition(x, y, z));
populator.addTileEntity(world, t);
}
}
} |
d9155d0d-1d05-4cc6-a710-fdb47fccd385 | 4 | public static boolean checkForBust(Dealer dealer, Player player) {
int playerScore = player.getDefaultScore();
int dealerScore = dealer.getDefaultScore();
// Both busted.
if(playerScore > twentyOne && dealerScore > twentyOne) {
System.out.println("Both have busted hands, so tie!");
tieSituation(player);
return true;
}
// Dealer busted.
else if(dealerScore > twentyOne) {
System.out.println("Dealer has a busted hand, so player wins!");
playerWon(player);
return true;
}
// Player busted.
else if(playerScore> twentyOne) {
System.out.println("Player has a busted hand, so dealer wins!");
dealerWon(dealer);
return true;
}
// Neither player busted.
else {
System.out.println("Neither dealer nor player has a busted hand.");
return false;
}
} |
80f6e9ec-0dc5-4820-a0b6-0d305778d32b | 7 | private void reInit() {
// fix/normalize url if possible
String newURL = AbstractPage.fixURLString(null, textFieldURL.getText());
//TODO: add normalization to path, creation of non-existing dirs request and such.
String newDir = textFieldDirectory.getText();
if (newURL == null) {
// fix failed, restoring current root url if one exists
// FIXME: maybe error status message and leave wrong text in place (for continued editing?)
if (rootPage != null) {
textFieldURL.setText(rootPage.url.toString());
textFieldDirectory.setText(rootPage.saveTo);
}
return;
}
// apply fix
textFieldURL.setText(newURL);
// check if no change happened
if (newURL.equals(rootPage.url.toString()) &&
newDir.equals(rootPage.saveTo)) {
// url and dir did not change.
initPrefetch(); // still full rescan.
return;
}
// now at least directory or URL changed --> drop old root and start anew
AbstractPage newRootPage = null;
try {
newRootPage = AbstractPage.bakeAPage(null, newURL, newDir, null);
} catch (IllegalArgumentException e) {
// fail to make a page out of newURL.
if (rootPage != null) {
textFieldURL.setText(rootPage.url.toString());
textFieldDirectory.setText(rootPage.saveTo);
}
}
if (newRootPage != null) {
rootPage = newRootPage;
setRootNodeForRootPage();
initPrefetch();
}
} |
7e19af53-8bea-4b43-ad76-d1d20c7cd9b5 | 1 | @Test
public void testLargeAmountOfNumbers(){
for(int i = 0; i < 2000; i++){
int input = (int)(Math.random()*100)*i;
int output = HashUtilities.shortHash(input);
int expected = input % 1000;
assertEquals(output, expected);
}
} |
0e28d77a-c13e-415d-b031-7f4c13f04877 | 2 | public Event getEvent(String s) {
if (s.length() == 3 && Info.isInteger(s)) {
return fetchEvent(Integer.parseInt(s));
}
return fetchEvent(s);
} |
9cd9c09f-b7c3-4ac4-b08d-055a52628fdf | 7 | public ListNode deleteDuplicates(ListNode head) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode itr = head;
ListNode itrNext = head;
ListNode itrPrev = head;
// {1,1}
// {1,1,1,1}
//1 1 2
while (itr.next != null) {
itrNext = itr.next;
itrPrev = itr;
boolean gotEnd = false;
while (itr.val == itrNext.val) {//itr point to the next neq node
if (itr.next != null) {
itr = itr.next;
itr.next = itrNext.next;
if (itr.next != null) {
itrNext = itr.next;
}else{
gotEnd = true;
break;
}
}
}
if(gotEnd){
itrPrev.next = null;
break;
}else{//itr point to last same number
itr = itrNext;//itr.next;
itrPrev.next = itr;
}
}
return head;
} |
ceecf14b-fcb1-431b-a594-7dc7df4e6ef4 | 8 | public void addBlock(String mat, BlockData blockData) {
String name = mat ;
if( blockData == null ) {
blockData = new BlockData(this) ;
}
// Register the MBean
ObjectName oName ;
try {
oName = new ObjectName("org.dkhenry.minejmx:type=BlockData,name="+name);
if( mbs.isRegistered(oName) ) {
mbs.unregisterMBean(oName) ;
}
mbs.registerMBean(blockData, oName) ;
} catch (InstanceAlreadyExistsException e) {
//e.printStackTrace();
} catch (MBeanRegistrationException e) {
//e.printStackTrace();
} catch (NotCompliantMBeanException e) {
//e.printStackTrace();
} catch (MalformedObjectNameException e) {
//e.printStackTrace();
} catch (NullPointerException e) {
//e.printStackTrace();
} catch (InstanceNotFoundException e) {
//e.printStackTrace();
}
this.blockData.put(name, blockData) ;
} |
3ed806e7-75d6-42f4-8b93-c9d73cb4d706 | 7 | @Override
public void update(GameContainer gc, StateBasedGame sbg, int delta)
throws SlickException {
// gestion de la souris
Input input = gc.getInput();
sourisX = input.getMouseX();
sourisY = input.getMouseY();
// parcours les items des options, pour voir si on est dessus
for (int i = 0; i < itemMort.length; i++) {
interieurBouton[i] = false;
if ((sourisX >= positionItemOption[i][0] && sourisX <= positionItemOption[i][0]
+ itemMort[i].getWidth())
&& (sourisY >= positionItemOption[i][1] && sourisY <= positionItemOption[i][1]
+ itemMort[i].getHeight())) {
itemMort[i].setAlpha(0.65f);
interieurBouton[i] = true;
} else
itemMort[i].setAlpha(1.f);
}
// Retour menu principal
if (interieurBouton[0] && input.isMousePressed(Input.MOUSE_LEFT_BUTTON)) {
sbg.enterState(RoboTech.MENUETAT);
}
} |
88bf59ee-d216-4cd2-b2f9-87df74ef74ed | 2 | public boolean isSelectedWidth()
{
for(int i=0;i<markers;i++)
{
if(marker[i].isSelectedWidth())
{
return true;
}
}
return false;
} |
0f4571e5-0af7-4b5c-be46-ef958184b54c | 1 | public String toString() {
String arrayString = "";
Occurrence temp = head;
while (head != null) {
arrayString = head.getDocName() + " " + head.getTermFrequency() + "; " + arrayString;
head = head.next;
}
head = temp;
return arrayString;
} |
c8375920-af0e-43ab-82cb-edf93d6de7fc | 0 | public void setStock(int stock) {
this.stock = stock;
} |
d6de0307-e50e-43f4-a321-92a0c741c482 | 5 | @Override
public void actionPerformed(ActionEvent a) {
if(a.getSource() == TypeSel){
Clear();
switch(TypeSel.getSelectedIndex()){
case posCartLine:
initCartesianLine();
break;
case posVecLine:
initVectorLine();
break;
case posCartPlane:
initCartesian();
break;
case posVecPlane:
initVector();
break;
default:
break;
}
}
this.update(true);
} |
9bd73a8b-a19f-40b0-a37e-a83327b744ed | 0 | public void removeKey(String c) {
synchronized(keychain) {
keychain.remove(c);
numKeys--;
}
} |
43dabc5a-1107-46b1-a6ea-1aee2fc4b65b | 5 | private MobileIdNameQuery<Npc> getAncestor() {
return ctx.npcs.select().select(new Filter<Npc>() {
@Override
public boolean accept(Npc npc) {
if (Arrays.binarySearch(ANCESTOR_IDS, npc.id()) >= 0) {
final Actor interacting = npc.interacting();
return (interacting == null || !npc.inCombat() || (interacting.equals(ctx.players.local()) && npc.healthPercent() > 0)) && ctx.movement.distance(options.getAreaSmall().getCentralTile(), npc) < 50;
}
return false;
}
}).first();
} |
30e108aa-7714-4267-ac12-a4d46a502034 | 5 | public static List<String> getLocalIPs() {
Enumeration<NetworkInterface> interfaces;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
return null;
}
List<String> ips = new ArrayList<String>();
while(interfaces.hasMoreElements()) {
NetworkInterface current = interfaces.nextElement();
if(current != null) {
Enumeration<InetAddress> addresses = current.getInetAddresses();
while(addresses.hasMoreElements()) {
InetAddress addr = addresses.nextElement();
if(addr != null) {
ips.add(addr.getHostAddress());
}
}
}
}
return ips;
} |
98bfe577-58e7-4937-8ac5-904b37fab36e | 3 | public int count(String key) {
if(key.equals(Defines.CURRENCY_NAME)){
return rangs;
}
int count = 0;
for(Item i : items){
if(key.equals(i.getName())){
count++;
}
}
return count;
} |
50092f00-e6e6-498e-9994-aff752a80d1f | 3 | @SuppressWarnings("static-access")
@EventHandler(priority = EventPriority.HIGH)
public void onMobDamage (EntityDamageByEntityEvent event) {
Entity entity = event.getEntity();
Entity damager = event.getDamager();
if (entity instanceof Player) {
if (damager instanceof Wolf) {
Player player = (Player) entity;
Wolf hound = (Wolf) damager;
if (MMHellhound.isHellhound(hound)) {
player.setFireTicks(30);
}
}
}
} |
b729bb2b-56eb-49fa-9afc-d6376ca1f9c6 | 0 | public Point3 neg(){
x = -x;
y = -y;
z = -z;
return this;
} |
f621233e-5917-484c-afd1-2a18737a88c4 | 4 | public ConnectedComponents(Graph<?> G) {
this.initId = 0;
this.id = new ListOrderedMap<>();
this.marked = new ListOrderedMap<>();
for (Object x : G.getAllVertices()) {
this.marked.put(x, false);
}
for (Object x : marked.keySet()) {
if (!this.marked.get(x)) {
dfs(G, x);
this.initId++;
}
}
} |
e428a417-9327-44e2-a50c-dafed96afba5 | 2 | public static List<String> readLines(InputStream in, Charset cs) throws IOException {
List<String> result = new ArrayList<String>();
cs = cs != null ? cs : Charset.defaultCharset();
BufferedReader lineReader = new BufferedReader(new InputStreamReader(in, cs));
try {
for (String line; ((line = lineReader.readLine()) != null); ) {
result.add(line);
}
} finally {
lineReader.close();
}
return result;
} |
c07aa311-9af3-42f0-80e1-6bf5a572a3df | 5 | private void jButton7ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton7ActionPerformed
// TODO add your handling code here:
liceu.Administrator admin = new liceu.Administrator();
try {
admin.addMaterie(materieDeAdaugat.getText());
} catch (IOException ex) {
Logger.getLogger(Administratorapp.class.getName()).log(Level.SEVERE, null, ex);
}
materieDeSters.removeAllItems();
BufferedReader fisier2;
try {
ArrayList<String> vector = new ArrayList<>();
fisier2 = new BufferedReader(new FileReader("fmaterii"));
for(String line; (line = fisier2.readLine())!= null;){
vector.add(line);
}
for(int i=0;i<vector.size();i++)
materieDeSters.addItem(vector.get(i));
} catch (FileNotFoundException ex) {
Logger.getLogger(Secretarapp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Secretarapp.class.getName()).log(Level.SEVERE, null, ex);
}
adaugareMaterie.dispose();
}//GEN-LAST:event_jButton7ActionPerformed |
ffa0a47d-d1e4-43aa-b5c2-10f499abe750 | 0 | public test()
{
// TODO Auto-generated constructor stub
} |
2144c54c-fa29-4693-a6d7-b82123c25ec4 | 0 | public void setWidth(int w){
width = w;
} |
00688040-f08a-41f3-9113-ac273cececa9 | 2 | public boolean canPlaceSettlement(VertexLocation vertLoc) {
//TESTING BUILDING ROAD, SETTLEMENT, CITY
// clientModel.getServerModel().getPlayers().get(0).setBrick(5);
// clientModel.getServerModel().getPlayers().get(0).setWood(5);
// clientModel.getServerModel().getPlayers().get(0).setWheat(5);
// clientModel.getServerModel().getPlayers().get(0).setSheep(5);
// clientModel.getServerModel().getPlayers().get(0).setOre(5);
// clientModel.getServerModel().getTurnTracker().setStatus("Playing");
//end test setup
if (state.getStatus().equals("FirstRound") || state.getStatus().equals("SecondRound"))
return clientModel.canBuildSettlement(playerInfo.getIndex(), vertLoc, true);
else
return clientModel.canBuildSettlement(playerInfo.getIndex(), vertLoc, false);
} |
70dea20a-9d1b-4dfe-a2f2-8d9be22a8c5a | 5 | public void removeNonUserRecords() throws SQLException
{
Collection<User> users = User.getUsers();
Collection<Integer> recordNumbers = GetRecords.create().getRecordNumbers();
Collection<Integer> toBeDeleted = new LinkedList<Integer>();
for (Integer recNumber : recordNumbers)
{
Record r = GetRecords.create().getRecord(recNumber);
boolean delete = true;
for (User user : users)
if (user.getID() == r.getOwner())
delete = false;
if (delete)
toBeDeleted.add(r.getNumber());
}
System.out.println("Deleting " + toBeDeleted.size() + " records");
for (Integer rec : toBeDeleted)
{
Record r = GetRecords.create().getRecord(rec);
System.out.println("Deleting " + r.getAuthor() + " - " + r.getTitle());
GetRecords.create().deleteRecord(r);
}
} |
16406b83-3ff5-4f1f-83d3-061113874890 | 9 | @Override
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof CommandKey)) {
return false;
}
CommandKey other = (CommandKey) obj;
if (main == null) {
if (other.main != null) {
return false;
}
} else if (!main.equals(other.main)) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
} |
8d85b4f0-d641-44b9-ad82-591740ccc1b9 | 9 | public String readLine() throws Exception {
int thisCode;
char thisChar;
String finalLine="";
// If our position is less than zero already, we are at the beginning
// with nothing to return.
if ( this.position < 0 ) {
return null;
}
for(;;) {
//System.err.println(this.position + " " +finalLine);
// we've reached the beginning of the file
if ( this.position < 0 ) {
break;
}
// Seek to the current position
this.randomfile.seek(this.position);
// Read the data at this position
thisCode=this.randomfile.readByte();
thisChar=(char)thisCode;
// If this is a line break or carrige return, stop looking
if (thisCode == 13 || thisCode == 10 ) {
// See if the previous character is also a line break character.
// this accounts for crlf combinations
this.randomfile.seek(this.position-1);
int nextCode=this.randomfile.readByte();
if ( (thisCode == 10 && nextCode == 13) || (thisCode == 13 && nextCode == 10) ) {
// If we found another linebreak character, ignore it
this.position=this.position-1;
}
// Move the pointer for the next readline
this.position--;
break;
} else {
// This is a valid character append to the string
finalLine=thisChar + finalLine;
}
// Move to the next char
this.position--;
}
// return the line
// return finalLine
return new String(finalLine.getBytes("Latin1"),"UTF8");
} |
9ea3d835-5c70-42aa-8491-2b80c56e51db | 3 | static final public Map<String,Object> propMapOf(Object... objs) {
HashMap<String, Object> m = new HashMap<>();
for (int i = 0; i < objs.length; i += 2) {
//String key = objs[i].toString();
Object keyObj = objs[i];
String key = (keyObj instanceof String)?(String)keyObj:keyObj.toString();
if (i + 1 < objs.length) {
Object value = objs[i + 1];
m.put(key, value);
} else {
m.put(key, null);
}
}
return m;
} |
b3df6813-fd1b-4936-99b7-f133547cbbc1 | 4 | private Spatial drawRingRopes() {
//TODO: Refactor this shit into a loop
Cylinder rope1 = new Cylinder(5, 5, 0.15f, 28, true);
Quaternion deg90 = new Quaternion();
deg90.fromAngleAxis(FastMath.PI / 2, new Vector3f(0f, 1f, 0f));
Node ropesNode = new Node("ropes");
//left
for (int i = 0; i < 3; i++) {
Geometry ropeGeo = new Geometry("Cylinder", rope1);
Material ropeMat = md.getAsset(MaterialDistributor.PATH_LIGHTING);
ropeMat.setFloat("Shininess", 12);
ropeMat.setBoolean("UseMaterialColors", true);
ropeMat.setColor("Ambient", ColorRGBA.Brown.mult(0.3f));
ropeMat.setColor("Diffuse", ColorRGBA.Brown.mult(0.35f));
ropeMat.setColor("Specular", ColorRGBA.Brown.mult(0.6f));
ropeGeo.setMaterial(ropeMat);
ropeGeo.setLocalTranslation(new Vector3f(-14f, 9f - (i * 2), 0f));
ropesNode.attachChild(ropeGeo);
}
//right
for (int i = 0; i < 3; i++) {
Geometry ropeGeo = new Geometry("Cylinder", rope1);
Material ropeMat = md.getAsset(MaterialDistributor.PATH_LIGHTING);
ropeMat.setFloat("Shininess", 12);
ropeMat.setBoolean("UseMaterialColors", true);
ropeMat.setColor("Ambient", ColorRGBA.Brown.mult(0.3f));
ropeMat.setColor("Diffuse", ColorRGBA.Brown.mult(0.35f));
ropeMat.setColor("Specular", ColorRGBA.Brown.mult(0.6f));
ropeGeo.setMaterial(ropeMat);
ropeGeo.setLocalTranslation(new Vector3f(14f, 9f - (i * 2), 0f));
ropesNode.attachChild(ropeGeo);
}
//Front
for (int i = 0; i < 3; i++) {
Geometry ropeGeo = new Geometry("Cylinder", rope1);
Material ropeMat = md.getAsset(MaterialDistributor.PATH_LIGHTING);
ropeMat.setFloat("Shininess", 12);
ropeMat.setBoolean("UseMaterialColors", true);
ropeMat.setColor("Ambient", ColorRGBA.Brown.mult(0.3f));
ropeMat.setColor("Diffuse", ColorRGBA.Brown.mult(0.35f));
ropeMat.setColor("Specular", ColorRGBA.Brown.mult(0.6f));
ropeGeo.setMaterial(ropeMat);
ropeGeo.setLocalRotation(deg90);
ropeGeo.setLocalTranslation(new Vector3f(0f, 9f - (i * 2), 14f));
ropesNode.attachChild(ropeGeo);
}
//BACK
for (int i = 0; i < 3; i++) {
Geometry ropeGeo = new Geometry("Cylinder", rope1);
Material ropeMat = md.getAsset(MaterialDistributor.PATH_LIGHTING);
ropeMat.setFloat("Shininess", 12);
ropeMat.setBoolean("UseMaterialColors", true);
ropeMat.setColor("Ambient", ColorRGBA.Brown.mult(0.3f));
ropeMat.setColor("Diffuse", ColorRGBA.Brown.mult(0.35f));
ropeMat.setColor("Specular", ColorRGBA.Brown.mult(0.6f));
ropeGeo.setMaterial(ropeMat);
ropeGeo.setLocalRotation(deg90);
ropeGeo.setLocalTranslation(new Vector3f(0f, 9f - (i * 2), -14f));
ropesNode.attachChild(ropeGeo);
}
return ropesNode;
} |
2b9b5571-57e6-49b2-9b42-c87d0c1ca159 | 6 | public static void main(String[] args) {
String inputFileName = null;
String outputFileName = null;
IParser parser = null;
INode root = null; // Root of the parse tree.
StringBuilder builder = null;
FileOutputStream stream = null;
OutputStreamWriter writer = null;
try {
try {
if (args.length < 2)
throw new Exception("Incorrect number of parameters to program.");
inputFileName = args[0];
outputFileName = args[1];
parser = new Parser();
parser.open(inputFileName);
root = parser.parse();
builder = new StringBuilder();
builder.append("PARSE TREE:\n");
root.buildString(builder, 0);
builder.append("\nEVALUATION:\n");
builder.append(root.evaluate(null));
stream = new FileOutputStream(outputFileName);
writer = new OutputStreamWriter(stream);
writer.write(builder.toString());
}
catch (Exception exception) {
System.out.println("EXCEPTION: " + exception);
}
finally {
if (parser != null)
parser.close();
if (writer != null)
writer.close();
if (stream != null)
stream.close();
}
}
catch (Exception exception) {
System.out.println("EXCEPTION: " + exception);
}
} |
2eef3141-6aa5-478a-a2f4-f63513dae14f | 1 | @Override
public void removeItems(Collection<String> items) {
try {
fTPConnector.deleteFiles(items);
items.removeAll(items);
} catch (IOException ioe) {
throw new RuntimeException(ioe);
}
} |
a6f96a64-b8c5-4de5-a365-c0061e7b69d0 | 5 | private static int[][] convertTo2D(BufferedImage image) {
final byte[] pixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData();
final int width = image.getWidth();
final int height = image.getHeight();
final boolean hasAlphaChannel = image.getAlphaRaster() != null;
int[][] result = new int[height][width];
if (hasAlphaChannel) {
final int pixelLength = 4;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += (((int) pixels[pixel] & 0xff) << 24); // alpha
argb += ((int) pixels[pixel + 1] & 0xff); // blue
argb += (((int) pixels[pixel + 2] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 3] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
} else {
final int pixelLength = 3;
for (int pixel = 0, row = 0, col = 0; pixel < pixels.length; pixel += pixelLength) {
int argb = 0;
argb += -16777216; // 255 alpha
argb += ((int) pixels[pixel] & 0xff); // blue
argb += (((int) pixels[pixel + 1] & 0xff) << 8); // green
argb += (((int) pixels[pixel + 2] & 0xff) << 16); // red
result[row][col] = argb;
col++;
if (col == width) {
col = 0;
row++;
}
}
}
return result;
} |
9878afb8-2451-432f-b353-71dd1a5cf4be | 5 | public static void unwrap(final String sourcePdfFile) throws FileNotFoundException, IOException
{
if (StringUtils.isBlank(sourcePdfFile))
{
throw new IllegalArgumentException();
}
Path sourcePath = Paths.get(sourcePdfFile);
if (Files.exists(sourcePath))
{
List<Path> listPdfFiles = null;
if (Files.isDirectory(sourcePath))
{
listPdfFiles = MoreFiles.listPdfFiles(sourcePath);
}
else if (Files.isRegularFile(sourcePath))
{
listPdfFiles = new ArrayList<>(Arrays.asList(sourcePath));
}
else
{
System.err.println("Verzeichnis oder Datei existiert nicht: " + sourcePdfFile);
return;
}
for (Path path : listPdfFiles)
{
System.out.println("Unwrap .. " + path.getFileName());
LangUtils.removePDFHeader(path.toString());
MoreFiles.renameFile(path.toString(), MoreFiles.removeExtension(path.toString(), "pdf"));
}
}
} |
d149872f-d423-4ba1-984b-0239963309ee | 5 | public Report callProbLogicEval_Module(Report report, String parameters, boolean onlyLocalHypotheses,int [] selectedItens ){
int countSelected=0;
int numberOftotalPOs = this.getNumberOfProofObligations();
for (int numberPo = 1; numberPo <= numberOftotalPOs; numberPo++) {
if( countSelected<selectedItens.length && selectedItens[countSelected]==numberPo-1){
countSelected++;
String proofObligation;
if(onlyLocalHypotheses)
proofObligation = this.getCleanProofObligationsWithLocalHypotheses(numberPo);
else
proofObligation = this.getGoalOfCleanExpandedProofObligations(numberPo);
if(parameters == null){
this.callProbLogicEval(true, false, report, numberPo , actualParameters, proofObligation);
} else{
this.callProbLogicEval(true, false, report, numberPo , parameters, proofObligation);
}
AutoDismiss.showMessageDialog(null, "Progress "+ countSelected+"/"+selectedItens.length+"\n"
+"The result is "+this.getResult()+"\n"
+proofObligation ,700);
System.out.println("\nThe result is "+ this.getResult()+" and progress "+ countSelected+"/"+selectedItens.length+"\n");
}
}
return report;
} |
12eb74dd-a581-411b-8abe-e045349b91ef | 6 | public static boolean justificationEqlP(Justification just1, Justification just2) {
return ((just1 == just2) ||
((just1.inferenceRule == just2.inferenceRule) &&
((just1.reversePolarityP == just2.reversePolarityP) &&
((((!(just1.inferenceRule == Logic.KWD_PRIMITIVE_STRATEGY)) &&
(!(just2.inferenceRule == Logic.KWD_PRIMITIVE_STRATEGY))) ||
(((PrimitiveStrategy)(just1)).strategy == ((PrimitiveStrategy)(just2)).strategy)) &&
Proposition.justificationPropositionsEqlP(just1.proposition, just1, just2.proposition, just2)))));
} |
56680161-3770-4fe8-99b8-349532724304 | 7 | public SimpleCommand request_next_move(boolean last_valid)
{
SimpleCommand c = new SimpleCommand();
if(next_move % 5 ==0)
{ //go forward, plow left
c.a = true;
c.b = true;
c.plow_left = true;
if(next_move % 10 == 0)
c.plow_left = false;
c.plow_straight = false;
}
else if(next_move % 5 ==1)
{ //go left, plow right (no left/down spill)
c.a = false;
c.b = true;
c.plow_left = false;
c.plow_straight = false;
}
else if(next_move % 5 ==2)
{ //go right, plow left (no right/down spill)
c.a = true;
c.b = false;
c.plow_left = true;
c.plow_straight = false;
}
else if(next_move % 5 ==3)
{ //go right, plow left (no right/down spill)
c.a = true;
c.b = false;
c.plow_left = true;
c.plow_straight = false;
}
else if(next_move % 5 ==4)
{ //go left, plow right (no left/down spill)
c.a = false;
c.b = true;
c.plow_left = false;
c.plow_straight = false;
}
next_move++;
if(next_move >= 61)
{
c.done = ":T: Reached end of run.";
}
return c;
} |
6b46df68-0674-4d51-944e-de6a0719ee14 | 5 | @Test
public void testForSmoke() throws Exception {
final List<String> messages=new ArrayList<String>();
//WebSocket ws=new WebSocket("ws://echo.websocket.org");
//ws.addRequestHeader("Origin", "http://websocket.org");
WebSocket ws=new WebSocket("ws://localhost:4080/echoserver");
ws.addRequestHeader("Origin", "http://localhost:4080");
ws.setWireProtocol(WireProtocolDraft03.INSTANCE);
ws.addListener(new WebSocket.EventListener() {
@Override
public void handleEvent(Event event) {
if (event.getType()==WebSocket.EVENT_MESSAGE) {
Message msg=event.getMessage();
if (msg.isText()) {
CharSequence text=msg.getMessageText();
System.out.println("Received message: " + text);
synchronized (messages) {
messages.add(text.toString());
messages.notify();
}
}
} else {
System.out.println("EVENT: " + event);
}
if (event.getType()==WebSocket.EVENT_ERROR) {
System.exit(1);
}
}
});
ws.start();
ws.send("Message 1");
ws.send("Message 2");
synchronized (messages) {
while (messages.size()<2 && ws.getReadyState()!=WebSocket.CLOSED) {
messages.wait();
}
}
// Should still be open at this point
assertEquals(WebSocket.OPEN, ws.getReadyState());
assertEquals("Message 1", messages.get(0));
assertEquals("Message 2", messages.get(1));
// Start close
ws.close();
ws.waitForReadyState(WebSocket.CLOSED);
System.out.println("Closed. ReadyState=" + ws.getReadyState());
Thread.sleep(1000);
} |
2fe1e1f1-4cea-480d-b199-1ac6378d6aa4 | 4 | @Override
public void recieveEvent(Event event) {
if (event.getEventType() == EventType.INPUT
&& !event.isHandled()) {
String input = (String) event.getData();
for(String trigger : triggers) {
if(input.startsWith(trigger)) {
emit(new Event(EventType.OUTPUT, this, buildMessage(input)));
event.markHandled();
}
}
}
} |
2aaee4c7-4595-497d-ac16-b38cf9531d40 | 5 | public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < 100; i++) {
list.add((int)(Math.random() * 50));
}
for (Integer value : list) {
System.out.println(value);
}
ArrayList<Integer> elderPeople = new ArrayList<Integer>();
for (Integer value : list) {
if(value <= 70) continue;
elderPeople.add(value);
}
list.removeAll(elderPeople);
for (Integer value : list) {
System.out.println(value);
}
} |
571efce5-5027-498e-a024-7190de4489bf | 2 | @Override
protected void paintComponent(Graphics g){
super.paintComponent(g);
setBackground(Color.BLACK);
PaintTiles(g);
g.setColor(Color.WHITE);
if (status==GameStatus.SHOTHIT)
g.drawString("You got 'em! YAAAY!", 120, 480);
else if (status==GameStatus.SHOTMISSED)
g.drawString("I'm gonna die down here...", 120, 480);
else
g.drawString(game.getRoomText(), 120, 480);
} |
beed862e-0e22-4e92-9fbb-c78373cd7d37 | 2 | public DefaultListModel<String> buildItemList() {
DefaultListModel<String> listModel = new DefaultListModel<String>();
for(int x = 0; x<itemDatabase.size(); x++) {
String[] temp = itemDatabase.get(x).split(";");
if(temp[0].startsWith("1"))
listModel.addElement(temp[0] + ": " + temp[1]);
}
return listModel;
} |
9ce7ce4e-a7b4-457e-ad9b-58db92726188 | 7 | public void run() {
// get line and buffer from ThreadLocals
SourceDataLine line = (SourceDataLine)localLine.get();
byte[] buffer = (byte[])localBuffer.get();
if (line == null || buffer == null) {
// the line is unavailable
return;
}
// copy data to the line
try {
int numBytesRead = 0;
while (numBytesRead != -1) {
// if paused, wait until unpaused
synchronized (pausedLock) {
if (paused) {
try {
pausedLock.wait();
}
catch (InterruptedException ex) {
return;
}
}
}
// copy data
numBytesRead =
source.read(buffer, 0, buffer.length);
if (numBytesRead != -1) {
line.write(buffer, 0, numBytesRead);
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
} |
e7631fd2-37f2-4248-9926-24c119133fd6 | 4 | public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {// parcour par colonne
case 0://colonne id_Stock
return Service.get(rowIndex).getId_sr();
case 1://colonne id_Stock
return Service.get(rowIndex).getPrix_sr();
case 2://colonne g
return Service.get(rowIndex).getType_sr();
case 3://colonne adresse depot
return Service.get(rowIndex).getId_ph();
default:
return null;
}
} |
8ad217c7-e581-44ba-8e47-441d4c80b9bc | 7 | public static MethodInvoker XMLToMethod(String _xmlString) {
SAXBuilder sxb = new SAXBuilder();
try {
InputStream stream = new ByteArrayInputStream(_xmlString.getBytes("UTF-8"));
Document doc = sxb.build(stream);
Element racine = doc.getRootElement();
String nomMethode = racine.getAttributeValue("method");
ArrayList<Class<?>> paramsType = new ArrayList<Class<?>>();
ArrayList<Object> paramsValue = new ArrayList<Object>();
for(Element param : racine.getChildren())
{
Class<?> c = Class.forName(param.getName());
paramsType.add(c);
XStream builder = new XStream(new StaxDriver());
builder.alias(param.getName(), c);
Object obj = builder.fromXML("<?xml version=\"1.0\"?><"+param.getName()+">"+param.getText()+"</"+param.getName()+">");
paramsValue.add(obj);
}
Class<?>[] classes = new Class[paramsType.size()];
for (int i=0; i<paramsType.size(); i++)
{
classes[i] = paramsType.get(i);
}
Method method = API.class.getMethod(nomMethode, classes);
MethodInvoker methodParam = new MethodInvoker(method, paramsValue.toArray());
return methodParam;
} catch (JDOMException | IOException | ClassNotFoundException | NoSuchMethodException | SecurityException e) {
e.printStackTrace();
}
return null;
} |
50afc581-2d50-467f-b3fc-462b64591ff9 | 2 | public List<Contato> listarContatos() {
try {
List<Contato> contatos = new ArrayList<Contato>();
PreparedStatement stmt = this.conexao.prepareStatement("select * from contato");
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
// criando o objeto Contato
Contato contato = new Contato();
contato.setId(rs.getInt("id"));
contato.setNome(rs.getString("nome"));
contato.setTelefone1(rs.getInt("tel_1"));
contato.setTelefone2(rs.getInt("tel_2"));
contato.setTelefone3(rs.getInt("tel_3"));
contato.setEmail(rs.getString("email"));
contato.setObservacoes(rs.getString("observacoes"));
// adicionando o objeto à lista
contatos.add(contato);
}
rs.close();
stmt.close();
return contatos;
} catch (SQLException e) {
throw new RuntimeException(e);
}
} |
0c4446e6-bd5f-4b56-8514-5d99c20e1863 | 5 | @Override
public void mouseDragged(float x, float y, MouseEvent e) {
if (active == null) {
// deligiere an moegliche untergruppen weiter
for (PolygonGroup i : subGroupsToInform) {
i.mouseDragged(x, y, e);
}
}
if (active != null) {
switch (mouseClickButton) {
case 1: {
moveObject(active, x, y);
break;
}
case 3: {
rotateObject(active, x, y);
break;
}
}
}
} |
77b8b14a-5667-48f8-8c48-ab2f1560332b | 7 | public void addEdge(S2Point v0, S2Point v1) {
// If xor_edges is true, we look for an existing edge in the opposite
// direction. We either delete that edge or insert a new one.
if (v0.equals(v1)) {
return;
}
if (options.getXorEdges()) {
Multiset<S2Point> candidates = edges.get(v1);
if (candidates != null && candidates.count(v0) > 0) {
eraseEdge(v1, v0);
return;
}
}
if (edges.get(v0) == null) {
edges.put(v0, HashMultiset.<S2Point>create());
}
edges.get(v0).add(v1);
if (options.getUndirectedEdges()) {
if (edges.get(v1) == null) {
edges.put(v1, HashMultiset.<S2Point>create());
}
edges.get(v1).add(v0);
}
} |
84a25925-51bb-4d85-9d12-47cca7229970 | 0 | public void clearGyro(){
_gyro.reset();
} |
6f69b2f6-168a-46da-b2e5-c5085e251e49 | 2 | @Override
public void keyReleased(KeyEvent e) {
int code = e.getKeyCode();
if (code > 0 && code < keys.length) {
keys[code] = false;
typed[code] = true;
}
} |
5549dcfc-1ff5-4f55-9e32-e9736782c191 | 9 | private boolean checkForEnd(byte data[]) {
if(data[0]==0&&data[1]==DATA) {
int i;
for(i = 4; i < data.length; i++) {
if(data[i] == 0) {
exitNext = true;
return false;
}
}
} else if(data[0]==0 && data[1]==ACK && exitNext) {
return true;
} else if(data[0]==0 && data[1]==5) {
return true;
}
return false;
} |
b5501555-3b6c-4c75-b8a5-07a9901bcbb8 | 7 | public static int redTicket( int a, int b, int c )
{
if ( a == 2 && b == 2 && c == 2 )
{
return 10;
}
if ( a == b && b == c )
{
return 5;
}
if ( a != b && a != c )
{
return 1;
}
return 0;
} |
f8f3dd5f-73e6-426c-8c99-815f9b9e944b | 5 | protected void writeHWReg(Size size, int addr, int value) {
int reg = addr - 0x2000;
if(mmap[reg] == null) {
mmap[reg] = new UnimplementedHardwareRegister();
Log.err(String.format("Write Memory Mapped register 0x%04x not implemented.", addr));
if (Settings.get(Settings.MEM_THROW_INVALID_ADDR).equals("true"))
throw new RuntimeException(String.format("Write Memory Mapped register 0x%04x not implemented.", addr));
}
if (size == Size.SHORT) {
if(mmap[reg+1] == null) {
mmap[reg+1] = new UnimplementedHardwareRegister();
Log.err(String.format("Write Memory Mapped register 0x%04x not implemented.", addr+1));
if (Settings.get(Settings.MEM_THROW_INVALID_ADDR).equals("true"))
throw new RuntimeException(String.format("Write Memory Mapped register 0x%04x not implemented.", addr+1));
}
/*
* Low goes first unless you want games to look like they're being
* played through Kanye's shutter shades.
*/
mmap[reg].setValue(value & 0x00FF);
mmap[reg+1].setValue((value & 0xFF00) >> 8);
} else {
mmap[reg].setValue(value);
}
} |
d40c7644-f40b-4957-9762-9e82c993bf41 | 1 | public static void remove() {
if (installed != null) {
Toolkit.getDefaultToolkit().removeAWTEventListener(installed);
}
installed = null;
} |
c307e1c1-6f1e-4ec4-82d4-49a8428f7e7f | 2 | private void parse(byte[] message) {
String[] exploded = explodeMessage(message);
function = Function.valueOf(exploded[0]);
if(exploded.length > 1)
uuid = exploded[1];
for (int i = 2; i < exploded.length; i++) {
parameters.add(Integer.parseInt(exploded[i]));
}
} |
16e0e0ce-3e8c-48ec-a8df-b33a1bde4482 | 7 | private int getTypeAccordingToFillMethod(TextGrid grid){
if(size() == 0) return TYPE_OPEN;
CellSet tempSet = copyCellSet(this);
tempSet.translate( -this.getMinX() + 1, -this.getMinY() + 1);
TextGrid subGrid = grid.getSubGrid(getMinX() - 1, getMinY() - 1, getWidth() + 3, getHeight() + 3);
AbstractionGrid abstraction = new AbstractionGrid(subGrid, tempSet);
TextGrid temp = abstraction.getCopyOfInternalBuffer();
TextGrid.Cell cell1 = null;
TextGrid.Cell cell2 = null;
int width = temp.getWidth();
int height = temp.getHeight();
TextGrid.Cell fillCell = null;
for(int y = 0; y < height; y++){
for(int x = 0; x < width; x++){
TextGrid.Cell cCell = temp.new Cell(x, y);
if(temp.isBlank(cCell)){
fillCell = cCell;
break;
}
}
}
if(fillCell == null){
System.err.println("Unexpected error: fill method cannot fill anywhere");
return TYPE_UNDETERMINED;
}
temp.fillContinuousArea(fillCell, '*');
if(VERBOSE_DEBUG) {System.out.println("Buffer after filling:"); temp.printDebug();}
if(temp.hasBlankCells()) return TYPE_HAS_CLOSED_AREA;
else return TYPE_OPEN;
} |
9462758a-a535-4b55-bde2-86fffb86ca8e | 0 | @Override
public void run() {
this.setPreferredSize(new Dimension(1024, 800));
this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
luoKomponentit(this.getContentPane());
this.pack();
this.setVisible(true);
} |
180411b0-b401-40ad-a7cb-ebcee7f09675 | 9 | public static String post(String adress,List<String> keys,List<String> values) throws IOException
{
String result = "";
OutputStreamWriter writer = null;
BufferedReader reader = null;
try
{
String data="";
if(keys != null && values != null)
for(int i=0;i<keys.size();i++)
{
if (i!=0) data += "&";
data +=URLEncoder.encode(keys.get(i), "UTF-8")+"="+URLEncoder.encode(values.get(i), "UTF-8");
}
URL url = new URL(adress);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
writer = new OutputStreamWriter(conn.getOutputStream());
writer.write(data);
writer.flush();
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String ligne;
int i = 0;
while ((ligne = reader.readLine()) != null)
{
result+=(i != 0 ? "\n" : "")+ligne;
i++;
}
}
catch (IOException e)
{
throw e;
}
finally
{
try
{
writer.close();
}
catch(Exception e)
{
;
}
try
{
reader.close();
}
catch(Exception e)
{
;
}
}
return result;
} |
0a4880bb-6bd3-4e0d-91ed-ff9f77d32df3 | 3 | @EventHandler
public void onSignChangeEvent(SignChangeEvent event) {
if (event.getLine(0).trim().equalsIgnoreCase("[filter]")) {
BlockFace direction = plugin.getSignBack(event.getBlock());
if (direction == null || event.getBlock().getRelative(direction).getType() != Material.HOPPER) {
event.getPlayer().sendMessage(ChatColor.RED + "[Filter] signs must be placed against hoppers.");
event.setCancelled(true);
return;
}
event.setLine(0, "[Filter]");
clearNearCache(event.getBlock());
Inventory inventory = getInventoryForSign(event.getBlock(), event.getLines());
event.getPlayer().openInventory(inventory);
}
} |
60d99440-4ead-4dc8-86bd-7f7aecbb152c | 2 | private void permute2Rec(int level, List<Integer> num, List<List<Integer>> res){
if (level == num.size()) res.add(new ArrayList<Integer>(num));
for (int i = level; i < num.size(); ++i){
Collections.swap(num, i, level);
permute2Rec(level + 1, num, res);
Collections.swap(num, i, level);
}
} |
159ceb0c-f78e-4dc6-8936-0702a0fa01e9 | 1 | @Test
public void testMissingType() throws Exception {
final Properties p = new Properties();
p.setProperty("type", "BOGUS");
final Properties[] configs = new Properties[]{p};
final FilterFactory ff = new FilterFactory(configs);
try {
final Filter[] filters = ff.getInstances(new MockConnectionProcessor());
} catch (Throwable t) {
Assert.assertEquals("failed to load class for Filter type 'BOGUS'", t.getMessage());
}
} |
046209f4-9699-443f-965c-c66779928e31 | 7 | public void run() {
// to loop until LOGOUT
boolean keepGoing = true;
while(keepGoing) {
// read a String (which is an object)
try {
cm = (ChatMessage) sInput.readObject();
}
catch (IOException e) {
display(username + " Exception reading Streams: " + e);
break;
}
catch(ClassNotFoundException e2) {
break;
}
// the messaage part of the ChatMessage
String message = cm.getMessage();
// Switch on the type of message receive
switch(cm.getType()) {
case ChatMessage.MESSAGE:
broadcast(username + ": " + message);
break;
case ChatMessage.LOGOUT:
display(username + " disconnected with a LOGOUT message.");
keepGoing = false;
break;
case ChatMessage.WHOISIN:
writeMsg("List of the users connected at " + sdf.format(new Date()) + "\n");
// scan al the users connected
for(int i = 0; i < al.size(); ++i) {
ClientThread ct = al.get(i);
writeMsg((i+1) + ") " + ct.username + " since " + ct.date);
}
break;
}
}
// remove myself from the arrayList containing the list of the
// connected Clients
remove(id);
close();
} |
3b9f3446-6d99-4fff-8f01-bda73ac23773 | 0 | public int getHP()
{
return hp;
} |
d794f65c-e7e3-47c1-8af1-0ec582826637 | 6 | public VgerBibData getBibData()
{
VgerHoldingDataGenerator holdingGen;
VgerItemDataGenerator itemGen;
makeConnection();
bibData = new VgerBibData();
bibData =
( VgerBibData ) new JdbcTemplate( ds ).queryForObject( BIB_QUERY,
new Object[]
{ getBibID() }, new VgerBibDataMapper() );
holdingGen = new VgerHoldingDataGenerator();
holdingGen.setDbName( getDbName() );
holdingGen.setBibID( getBibID() );
bibData.setYrlHoldings( holdingGen.getItems() );
itemGen = new VgerItemDataGenerator();
itemGen.setDbName( getDbName() );
itemGen.setBibID( getBibID() );
itemGen.setItemIDs( getItemIDs() );
bibData.setSrlfItems( itemGen.getSimpleItems() );
if ( bibData.getSrlfItems() != null && bibData.getSrlfItems().size() > 0 )
{
if ( bibData.getSrlfItems().get( 0 ).getPickupLocale().contains( "Biomedical" ) )
isBio = true;
else
isBio = false;
}
else if ( bibData.getYrlHoldings() != null && bibData.getYrlHoldings().size() > 0 )
{
if ( bibData.getYrlHoldings().get( 0 ).getPickupLocale().contains( "Biomedical" ) )
isBio = true;
else
isBio = false;
}
else
{
isBio = false;
}
return bibData;
} |
9c4fe9f4-060d-4432-a676-c3953bbf8872 | 9 | public FinishedJobRecord(String str) {
StringTokenizer st = new StringTokenizer(str, ":");
int tokNumber = 0;
while (st.hasMoreElements()) {
tokNumber++;
String val = st.nextToken();
// We only get what we need, fields which are not used by
// pipeline will not be initialized.
switch (tokNumber) {
case 1:
qname = val;
break;
case 6:
job_number = val;
break;
case 36:
task_number = Integer.parseInt(val);
break;
case 10:
start_time = Long.parseLong(val) * 1000;
break;
case 11:
end_time = Long.parseLong(val) * 1000;
break;
case 13:
exit_status = Integer.parseInt(val);
break;
case 15:
ru_utime = val;
break;
case 16:
ru_stime = val;
break;
}
}
} |
12992d16-83b1-4f6c-938a-71f47dfd3c59 | 5 | private void initGraphics() {
startX = PREFERRED_WIDTH * 0.114;
startY = PREFERRED_WIDTH * 0.112;
stepX = PREFERRED_WIDTH * 0.072;
stepY = PREFERRED_WIDTH * 0.08;
font = Font.loadFont(getClass().getResourceAsStream("/eu/hansolo/enzo/fonts/din.otf"), PREFERRED_WIDTH * 0.048);
background = new Region();
background.getStyleClass().addAll("background", getSkinnable().getColor().STYLE_CLASS);
stainlessBackground.setImage(texture.getImage(PREFERRED_WIDTH, PREFERRED_HEIGHT));
stainlessBackground.setOpacity(getSkinnable().getColor() == QlockTwo.QlockColor.STAINLESS_STEEL ? 1 : 0);
p1 = new Region();
p1.getStyleClass().add("dot-off");
p2 = new Region();
p2.getStyleClass().add("dot-off");
p3 = new Region();
p3.getStyleClass().add("dot-off");
p4 = new Region();
p4.getStyleClass().add("dot-off");
highlight = new Region();
highlight.getStyleClass().add("highlight");
matrix = new Label[11][10];
for (int y = 0 ; y < 10 ; y++) {
for (int x = 0 ; x < 11 ; x++) {
matrix[x][y] = new Label();
matrix[x][y].setAlignment(Pos.CENTER);
matrix[x][y].setPrefWidth(PREFERRED_WIDTH * 0.048);
matrix[x][y].setPrefHeight(PREFERRED_HEIGHT * 0.048);
matrix[x][y].setText(getSkinnable().getQlock().getMatrix()[y][x]);
matrix[x][y].setFont(font);
matrix[x][y].getStyleClass().add("text-off");
}
}
pane.getChildren().setAll(background,
stainlessBackground,
p4,
p3,
p2,
p1);
for (int y = 0 ; y < 10 ; y++) {
for (int x = 0 ; x < 11 ; x++) {
pane.getChildren().add(matrix[x][y]);
}
}
pane.getChildren().add(highlight);
getChildren().setAll(pane);
resize();
} |
adf2c0c3-25be-4536-b15b-30f2aec61662 | 3 | public static ArrayList<Rating> getTestSet(String file) {
ArrayList<Rating> testset = new ArrayList<Rating>();
InputStream fis = null;
BufferedReader br;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
br = new BufferedReader(new InputStreamReader(fis,
Charset.forName("UTF-8")));
try {
String line;
while ((line = br.readLine()) != null) {
// Deal with the line
String fields[] = line.split(",");
Rating r = new Rating();
r.user = Long.parseLong(fields[0]);
r.item = Long.parseLong(fields[1]);
r.rating = Float.parseFloat(fields[2]);
testset.add(r);
}
br.close();
fis.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return testset;
} |
394aaff0-1888-489f-8d3f-92063e2d289b | 6 | @MCCommand(cmds = { "addOptions" }, op = true, usage = PORT_ADD_OPTIONS)
public boolean portAddOptions(CommandSender sender, Port port, String[] args)
{
List<String> portOptions = new ArrayList<String>();
for (int i = 2; i < args.length; i++)
{
String op = args[i];
if (!Port.checkOption(op))
{
sendMessage(sender, "Port Option " + args[i]
+ " is not a valid option");
sendValidOptions(sender);
return true;
}
portOptions.add(op);
}
if (port.hasOption(PortOption.FIRSTUSE))
{
if (!(sender instanceof Player))
{
return sendMessage(sender,
"&cYou need to be ingame to use this option");
}
Player p = (Player) sender;
try
{
port.setDestination2(p.getLocation());
}
catch (Exception e)
{
return sendMessage(sender,
"&4Cant set destination to be within the source");
}
}
for (String op : portOptions)
{
port.addOptions(op);
}
return sendMessage(sender, "&eAdded options " + portOptions);
} |
6be62807-2e1a-4b75-ab99-664f62ec2308 | 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(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(Estadisticas.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(Estadisticas.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 Estadisticas().setVisible(true);
Best.setText("");
Best.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/Blues.png")));
MoreSell.setText("");
MoreSell.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/MoreSell.png")));
NoSell.setText("");
NoSell.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/MinSell.png")));
Salir.setText("");
Salir.setIcon(new ImageIcon(this.getClass().getResource("/Imagen/Salir.png")));
}
});
} |
89b8da4b-1930-4fcd-a2d3-e6bc7ef31781 | 8 | public String getCardTypeString()
{
String ret = "";
switch (cardType)
{
case HERO_FRONT:
ret = "Hero Front"; break;
case HERO_BACK:
ret = "Hero Back"; break;
case HERO_CARD:
ret = "Hero Card"; break;
case VILLAIN_FRONT:
ret = "Villain Character"; break;
case VILLAIN_BACK:
ret = "Villain Character"; break;
case VILLAIN_CARD:
ret = "Villain Card"; break;
case ENVIRONMENT_CARD:
ret = "Environment Card"; break;
case CARD_BACK:
ret = "Card Back"; break;
}
return ret;
} |
e1d8f1a5-f045-4ce0-879b-f6d6631c97f6 | 9 | public void nextFrame() {
if (loopCount < 0)
return;
int n = images != null ? images.length : 0;
if (n <= 1)
return;
if (gifDecoder == null)
return;
currentTime = System.currentTimeMillis();
if (previousFrameTime != 0L) {
if (currentTime - previousFrameTime >= getDelayTime(frameCounter)) {
frameCounter++;
if (frameCounter == n) {
if (loopCount == 0) {
frameCounter = 0;
}
else {
if (loopCounter < loopCount - 1) {
frameCounter = 0;
loopCounter++;
}
else {
frameCounter = n - 1;
}
}
}
previousFrameTime = currentTime;
}
}
else {
previousFrameTime = currentTime;
}
} |
c5e97da1-8267-43b2-804e-9089b37deb5c | 8 | protected Point2D checkWallCollision(float newX, float newY) {
float fromX = Math.min(getPosition().getX(), newX);
float toX = Math.max(getPosition().getX() + getWidth(), newX + getWidth());
float fromY = Math.min(getPosition().getY(), newY);
float toY = Math.max(getPosition().getY() + getHeight(), newY + getHeight());
int fromTileX = (int)(fromX / game.getTileWidth());
if (fromTileX < 0) fromTileX = 0;
int toTileX = (int)(toX / game.getTileWidth());
int fromTileY = (int)(fromY / game.getTileHeight());
if (fromTileY < 0) fromTileY = 0;
int toTileY = (int)(toY / game.getTileHeight());
Tile[][] walls = game.getTiles();
for (int x = fromTileX; x <= toTileX && x < game.getNumTilesX(); x++) {
for (int y = fromTileY; y <= toTileY && y < game.getNumTilesY(); y++) {
Tile tile = walls[x][y];
if (tile != null && collidesWith(tile)) {
// System.out.println("Detected Wall Collision");
// System.out.println("CurrPos: " + getPosition().getX() + ":" + getPosition().getY());
// System.out.println("NewPos: " + newX + ":" + newY);
// System.out.println("fromTileX: " + fromTileX + " toTileX: " + toTileX);
// System.out.println("fromTileY: " + fromTileY + " toTileY: " + toTileY);
// System.out.println("Collided with tile at: " + x + ":" + y);
// System.out.println("Tile pixel posx " + x * Wall.SIZE + " width: " + Wall.SIZE);
// System.out.println("Tile pixel posy " + y * Wall.SIZE + " height: " + Wall.SIZE);
return tile.getPosition();
}
}
}
return null;
} |
c93eb8ed-b834-4014-8443-b08b3282365b | 4 | public String the(String field)
{
String newField = "", number = "";
if(field.substring(0, 1).equals(" "))
{
field.substring(1);
}
for(int i = 1; i <= field.length(); i++)
{
if(isNumber(field.substring(i - 1, i)))
{
number = number + field.substring(i - 1, i);
}
else if(field.substring(i - 1, i).equals(" "))
{
newField = "#" + number;
number = "";
}
else
{
newField = "~invalid~";
break;
}
}
newField = number + newField;
return newField;
} |
bef3ab73-bf4c-411d-8198-4f47819ca547 | 2 | public boolean clicked() {
if(key.isPressed() && !key.isHeld())
return true;
else
return false;
} |
320526ee-7e2f-454b-afad-c8f77998802e | 7 | private static void initialize(int size) {
greatestFactor = new int[size];
// wheel factorization (sort of...)
greatestFactor[1] = 1;
for (Integer seed : seeds) {
for (int i = seed; i < size; i += seed) {
greatestFactor[i] = seed;
}
}
// now do modified Sieve of Er...
int sqrt = (int) Math.floor(Math.sqrt(size) + 1);
for (int prime = 2; prime < sqrt; prime++) {
if (0 == greatestFactor[prime]) {
for (int i = prime; i < size; i += prime) {
greatestFactor[i] = prime;
}
}
}
// now flesh out the rest of the sieve.
for (int i = sqrt; i < size; i++) {
if (0 == greatestFactor[i]) {
greatestFactor[i] = i;
}
}
} |
dba3ba07-ea32-4e93-a8c2-0ca3ad9b4822 | 7 | protected void generateInstructions(List<Instruction> instructions) {
for (Instruction instruction : instructions) {
m_currentInstruction = instruction.toString();
print(LABEL_PREFIX + m_instructionCounter++ + ": # " + m_currentInstruction);
indent();
if (instruction instanceof Assign) {
generateAssign((Assign) instruction);
} else if (instruction instanceof If) {
generateIf((If) instruction);
} else if (instruction instanceof Repeat) {
generateRepeat((Repeat) instruction);
} else if (instruction instanceof Read) {
generateRead((Read) instruction);
} else if (instruction instanceof Write) {
generateWrite((Write) instruction);
} else if (instruction instanceof Call) {
generateCall((Call) instruction);
}
removeIndent();
}
} |
7baebc9a-5897-4a70-90d9-891c9e086916 | 5 | public void initTable () {
int[] fArray = {45,120,80,45,150,150,45,150,150,150,200,150,150,150,150,150,150};
for (int i=0; i<= table_fullticket.getColumnCount()-1; i++) {
table_fullticket.getColumnModel().getColumn(i).setPreferredWidth(fArray[i]);
}
int [] cArray = {45,150,150,150,220,150,270};
for (int i=0; i<= table_customer.getColumnCount()-1; i++) {
table_customer.getColumnModel().getColumn(i).setPreferredWidth(cArray[i]);
}
int[] eArray = {45,150,150,150,130,250};
for (int i=0; i<= table_employee.getColumnCount()-1; i++) {
table_employee.getColumnModel().getColumn(i).setPreferredWidth(eArray[i]);
}
int[] pArray = {45, 200, 800};
for (int i=0; i<= table_product.getColumnCount()-1; i++) {
table_product.getColumnModel().getColumn(i).setPreferredWidth(pArray[i]);
}
int[] hArray = {70,150,150,700};
for (int i=0; i<= table_history.getColumnCount()-1; i++) {
table_history.getColumnModel().getColumn(i).setPreferredWidth(hArray[i]);
}
} |
6990f636-7db9-41a2-9e6b-fa60ff41eb54 | 8 | protected static Request createRequest(RequestType type) {
switch(type) {
case COMPARE_AND_SET: return new CompareAndSetRequest();
case ADD_AND_GET: return new AddAndGetRequest();
case UPDATE: return new UpdateRequest();
case GET_OR_CREATE: return new GetOrCreateRequest();
case DELETE: return new DeleteRequest();
case SET: return new SetRequest();
case RECONCILE: return new ReconcileRequest();
case RESEND_PENDING_REQUESTS: return new ResendPendingRequests();
default: throw new IllegalArgumentException("failed creating a request from " + type);
}
} |
52cff926-6a8a-4ef0-a2bb-74908cba1b11 | 6 | public void amountDecremented(int ID)
{
switch (ID)
{
case 0:
case 1:
case 2:
case 3:
bonusStats++;
characterStr.updateMaxStats(characterStr.count + bonusStats, 18);
characterInt.updateMaxStats(characterInt.count + bonusStats, 18);
characterDex.updateMaxStats(characterDex.count + bonusStats, 18);
characterCon.updateMaxStats(characterCon.count + bonusStats, 18);
break;
case 4:
case 5:
bonusSkills++;
skill1control.updateMaxStats(skill1control.count + bonusSkills, 99);
skill2control.updateMaxStats(skill2control.count + bonusSkills, 99);
skill3control.updateMaxStats(skill2control.count + bonusSkills, 99);
break;
}
} |
fc7b2908-6d94-4d3a-ae9f-a4cd9265ffc0 | 3 | public void updatePrintField(){
ArrayList<LinkedList<Steinchen>> spielfeld = controller.getPlayground().getField();
for(int i = 0; i < 24; i++){
for(int j = 0; j < spielfeld.get(i).size(); j++){
if(spielfeld.get(i).get(j) != null){
print(spielfeld.get(i).get(j).getSteinchenID());
}
}
}
} |
64326ca6-3067-456d-a501-2722293299a5 | 3 | public boolean offScreen() {
return x + xMap + width < 0 || x + xMap - width > Game.WIDTH
|| y + yMap + height < 0 || y + yMap - height > Game.HEIGHT;
} |
d238e684-a0cc-4734-82e5-6b71779fe672 | 2 | public boolean listEntry(int value) {
ListElement current = head;
while (current != tail.next) {
if (current.value == value) {
return true;
}
}
return false;
} |
4a0091dd-2c19-4668-a1c4-712aff6f6d5c | 1 | public int getPrice()
{
int price;
if (_shots > 0)
{
price = _price;
} else
{
price = GameSettings.SOLD_OUT_PRICE;
}
return price;
} |
d6a68758-4fb2-4ff4-bbd6-65f7be714318 | 9 | @Override
public ClusteringOperation next()
{
byte opCode = this.opCodes.get(++opIndex);
ClusteringOperation result = null;
if (opCode == 0)
{
result = ClusteringOperation.newNextStepOp();
}
else if (opCode == 1 || opCode == 2 || opCode == 3 || opCode == 4)
{
int arg0 = this.intArgs.get(++argIndex);
int arg1 = this.intArgs.get(++argIndex);
int arg2 = this.intArgs.get(++argIndex);
switch (opCode)
{
case ((byte) 1):
result = ClusteringOperation.newMergeOp(arg0, arg1, arg2);
break;
case ((byte) 2):
result = ClusteringOperation.newSplitOp(arg0, arg1, arg2);
break;
case ((byte) 3):
result = ClusteringOperation.newMergeDoneOp(arg0, arg1, arg2);
break;
case ((byte) 4):
result = ClusteringOperation.newSplitDoneOp(arg0, arg1, arg2);
break;
}
}
return result;
} |
cd3f61d0-3f6e-4e4a-9403-9277750530b6 | 6 | private void vakautaKeko() {
/* taulukon koko pitäisi teoriassa olla oikeasti:
keon suurinasteisen puun aste +1 */
FibonacciSolmu[] A = new FibonacciSolmu[keonKoko];
FibonacciSolmu kasiteltava = min;
kasiteltava = kasiteltava.getLeft();
int juurienMaara = 1;
while (kasiteltava != min) {
juurienMaara++;
kasiteltava = kasiteltava.getLeft();
}
for (int i=0; i<juurienMaara; i++) {
kasiteltava = lisaaJuuretTaulukkoon(kasiteltava, A);
}
min = null;
for (int i=0; i<keonKoko; i++) {
if (A[i] != null) {
if (min == null) {
min = A[i];
}
else {
lisaaSolmuSolmulistaan(A[i], this);
if (A[i].getArvo() < min.getArvo()) {
min = A[i];
}
}
}
}
} |
3eb27224-c10b-4aeb-b336-e02fcf811384 | 8 | public static int countNeighbours(boolean [][] world, int col, int row){
int total = 0;
total = getCell(world, col-1, row-1) ? total + 1 : total;
total = getCell(world, col , row-1) ? total + 1 : total;
total = getCell(world, col+1, row-1) ? total + 1 : total;
total = getCell(world, col-1, row ) ? total + 1 : total;
total = getCell(world, col+1, row ) ? total + 1 : total;
total = getCell(world, col-1, row+1) ? total + 1 : total;
total = getCell(world, col , row+1) ? total + 1 : total;
total = getCell(world, col+1, row+1) ? total + 1 : total;
return total;
} |
4ba8f82e-8921-4ce1-a00e-76bf49c5f6f7 | 9 | public synchronized void piece(int index, int begin, byte[] block, Peer peer) {
RequestExtended request = null;
Set<RequestExtended> pendingRequests = null;
pendingRequests = peerPendingRequests.get(peer);
if (pendingRequests != null){
for (RequestExtended re : pendingRequests){
if (re.getIndex() == index && re.getBegin() == begin && re.getLength() == block.length){
request = re;
break;
}
}
if (request != null){
pendingRequests.remove(request);
if (pendingRequests.size() == 0)
peerPendingRequests.remove(peer);
request.getPeers().remove(peer);
/*
* Cancel the same request to all the other peers
*/
for (Peer p : request.getPeers()) {
p.sendMessage(new Cancel(index,begin,block.length));
pendingRequests = peerPendingRequests.get(p);
pendingRequests.remove(request);
if (pendingRequests.size() == 0)
peerPendingRequests.remove(p);
}
piecePendingRequests.get(index).remove(request);
allPendingRequests.remove(request);
}
}
/*
* else, the peer is sending us a block we didn't request
* or a block we already canceled
*/
} |
28b04664-1374-4512-8911-114013c1f4a8 | 5 | @Override
public void buttonPerformed(String name) {
if (name.equals("Choose Colour")) {
Color temp = JColorChooser.showDialog(null, "Choose your line color", c);
if (temp != null) {
c = temp;
}
} else if (name.equals("Save")) {
writeMap();
} else if (name.equals("Place Character")) {
setChar = true;
} else if (name.equals("Exit")) {
System.exit(0);
}
} |
c6be1660-c879-4341-b796-75bbf5bb2441 | 6 | public static void loadSQLStatements(List<SQLStatement> sqlStatementsToLoad) {
Connection connection = null;
try {
connection = ConnectionPoolUtils.getConnectionFromPool();
if (connection == null) {
// just for testability: during normal execution we will never get here. But the unit tests are
// running without a database
return;
}
PreparedStatement sqlTextStatement = connection.prepareStatement(SELECT_SQL_TEXT_FOR_200_STATEMENTS);
sqlTextStatement.setFetchSize(1000);
int indexPlaceholder = 1;
for (SQLStatement currentStatement : sqlStatementsToLoad) {
sqlTextStatement.setString(indexPlaceholder, currentStatement.getSqlId());
indexPlaceholder++;
if (indexPlaceholder > NUMBER_BIND_VARIABLES_SELECT_SQL_TEXT) {
// all place holders are filled - so fetch the sql text from the db
getTextFromDB(sqlTextStatement);
indexPlaceholder = 1;
}
}
if (indexPlaceholder > 1) {
// there are some statements left...
// fill the empty bind variables with invalid IDs
for (int index = indexPlaceholder; index <= NUMBER_BIND_VARIABLES_SELECT_SQL_TEXT; index++) {
sqlTextStatement.setString(index, "");
}
getTextFromDB(sqlTextStatement);
}
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, e);
} finally {
ConnectionPoolUtils.returnConnectionToPool(connection);
}
} |
3f2b066f-d781-4d9b-b8ce-529e0ad46984 | 5 | private static void setFinder(Entry entry) {
// Eat any exception we might encounter - if this fails it'll just revert to creating
// a new JAXBContext each time. This is slow but works.
try {
Method method = entry.getClass().getDeclaredMethod("setFinder", JAXBContextFinder.class); //$NON-NLS-1$
method.setAccessible(true);
method.invoke(entry, finder);
} catch (SecurityException e) {
} catch (IllegalArgumentException e) {
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (NoSuchMethodException e) {
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.