method_id stringlengths 36 36 | cyclomatic_complexity int32 0 9 | method_text stringlengths 14 410k |
|---|---|---|
32fdb486-644a-474a-a2f5-998bf4e193c9 | 8 | public int findIndexLetter(char ch)
{
if(Character.toLowerCase(ch)=='a') {return 0;}
if(Character.toLowerCase(ch)=='b') {return 1;}
if(Character.toLowerCase(ch)=='c') {return 2;}
if(Character.toLowerCase(ch)=='d') {return 3;}
if(Character.toLowerCase(ch)=='e') {return 4;}
if(Character.toLowerCase(ch)=='f') {return 5;}
if(Character.toLowerCase(ch)=='g') {return 6;}
if(Character.toLowerCase(ch)=='h') {return 7;}
return -1;
} |
4b8bd8a6-9947-4217-a24f-62b564627858 | 3 | public static void setQtCaddie (String idr, char signe) throws BDException {
String requete = null;
if (signe != 'd')
requete = "update lecaddie set qt = (select qt from lecaddie where idr="+idr+")"+signe+"1 where idr="+idr;
else
requete = "delete from lecaddie where idr="+idr;
Statement stmt = null;
Connection conn = null;
try {
conn = BDConnexion.getConnexion();
stmt = conn.createStatement();
int nb_insert = stmt.executeUpdate(requete);
if(nb_insert != 1)
throw new BDException("Problème dans la mise à jour d'une quantité du caddie");
conn.commit();
} catch (SQLException e) {
throw new BDException("Problème dans la mise à jour d'une quantité du caddie (Code Oracle : "+e.getErrorCode()+")");
}
finally {
BDConnexion.FermerTout(conn, stmt, null);
}
} |
f1496bf3-c270-45fd-bdba-794b83618639 | 0 | public int GetRecentBus()
{
return recentBus;
} |
25dfc95d-0205-43cc-bfb6-508fde1ea731 | 7 | public void tick() {
int xa = 0;
int ya = 0;
if (input.isMovingWithKey) {
if (input.up) ya--;
if (input.down) ya++;
if (input.left) xa--;
if (input.right) xa++;
} else {
xa = input.mouseX;
ya = input.mouseY;
}
if (xa != 0 || ya != 0) {
move(xa, ya);
}
} |
6637b63a-9fbf-4cdc-afa8-e2fdd2f5d8ce | 0 | @Override
public int getYearsExperience() {
return super.getYearsExperience();
} |
768d188c-593e-4340-9a12-ed0b0fe11b02 | 6 | public void run() {
timeUntilStart = 120;
while (Status.isStatus(Status.IN_LOBBY)) {
for (; timeUntilStart >= 0; timeUntilStart--) {
if (timeUntilStart == 0) {
// Hier begint de game
break;
}// Dit zorgt ervoor dat er om de 10 sec gebroadcast wordt
// hoelang het nog duurt
if (timeUntilStart % 10 == 0 || timeUntilStart < 10) {
ChatManager.broadcast(timeUntilStart
+ " seconds until the game is starting!");
}
// Dit zorgt ervoor dat de Runnable niet gaat buggen en crashen
// xd
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
Bukkit.shutdown();
}
}
}
} |
85801db7-8009-4e4a-8748-38c56fbf21b6 | 1 | @Override
public void addCategory(Category category) {
PreparedStatement pStmt = null;
try {
pStmt = conn.prepareStatement("INSERT INTO CATEGORY (description) VALUES (?);");
pStmt.setString(1, category.getDescription());
pStmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeResource(pStmt);
}
} |
c8f9b70d-c35d-4d65-a173-31cc680c9c1b | 3 | private void key(byte key[]) {
int i;
int koffp[] = { 0 };
int lr[] = { 0, 0 };
int plen = P.length, slen = S.length;
for (i = 0; i < plen; i++)
P[i] = P[i] ^ streamtoword(key, koffp);
for (i = 0; i < plen; i += 2) {
encipher(lr, 0);
P[i] = lr[0];
P[i + 1] = lr[1];
}
for (i = 0; i < slen; i += 2) {
encipher(lr, 0);
S[i] = lr[0];
S[i + 1] = lr[1];
}
} |
86267132-a5d7-4601-bd9e-46f3e7bd7d5a | 5 | @BeforeTest
@Test(groups = { "BST", "Insertion" })
public void testBSTInsertion() throws DuplicateKeyException {
Integer count = 0;
Reporter.log("[ ** BST Insertion ** ]\n");
try {
timeKeeper = System.currentTimeMillis();
for (int i = 0; i < seed; i++) {
bTree.put(randomArray[i], randomCharArray[i]);
}
Reporter.log("Insert -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
timeKeeper = System.currentTimeMillis();
for (Integer i = 0; i < seed; i++) {
try {
bTree.put(i, 'r');
} catch (DuplicateKeyException e) {
count++;
}
}
if (count == seed) {
Reporter.log("Fake Insert -- Passed : "
+ (System.currentTimeMillis() - timeKeeper) + " ms\n");
} else {
throw new DuplicateKeyException();
}
} catch (DuplicateKeyException e) {
Reporter.log("Insertion -- Failed!!!\n");
throw e;
}
} |
82c50838-a276-45a4-86cc-c5ccef333a92 | 3 | public List<String> getQueryNames() {
List<String> names = new ArrayList<String>();
try {
NodeList nodes = Utilities.selectNodes(this.doc, "/c:settings/c:queries/c:query", this.namespaces);
if(nodes != null) {
for(int i = 0; i < nodes.getLength(); ++i) {
Node node = nodes.item(i);
Attr attr = (Attr) node.getAttributes().getNamedItemNS(Settings.DEFAULT_NAMESPACE, "name");
names.add(attr.getValue());
}
}
} catch (XPathExpressionException e) {
logger.warn("Unable to get the query names.");
names = null;
}
return names;
} |
cd2ffb04-7807-4a23-a908-0d314456ce7c | 6 | @EventHandler
public void ZombiePoison(EntityDamageByEntityEvent event) {
Entity e = event.getEntity();
Entity damager = event.getDamager();
String world = e.getWorld().getName();
boolean dodged = false;
Random random = new Random();
double randomChance = plugin.getZombieConfig().getDouble("Zombie.Poison.DodgeChance") / 100;
final double ChanceOfHappening = random.nextDouble();
if (ChanceOfHappening >= randomChance) {
dodged = true;
}
if (plugin.getZombieConfig().getBoolean("Zombie.Poison.Enabled", true) && damager instanceof Zombie && e instanceof Player && plugin.getConfig().getStringList("Worlds").contains(world) && !dodged) {
Player player = (Player) e;
player.addPotionEffect(new PotionEffect(PotionEffectType.POISON, plugin.getZombieConfig().getInt("Zombie.Poison.Time"), plugin.getZombieConfig().getInt("Zombie.Poison.Power")));
}
} |
613426c9-b7ba-4e3a-9298-911e24a7e241 | 9 | public static void testOrchestrator(int maxIterations) {
int climateControlErrorCounter = 0;
int climateControlEventCounter = 0;
int dailyWakeupErrorCounter = 0;
int dailyWakeupEventCounter = 0;
int luminanceManagementErrorCounter = 0;
int luminanceManagementEventCounter = 0;
for (int i=0; i<maxIterations; i++) {
// INITIAL EVENT SCHEDULING
Error res = Error.NO_EVENT;
TimerEvent a = new TimerEvent(WakeReason.DAILY_WAKEUP);
timers.add(a);
Orchestrator_part2.setArtificialClimateControlPortType(acc);
Orchestrator_part2.setNaturalClimateSystemPortType(nc);
Orchestrator_part2.setPathsPortType(p);
Orchestrator_part2.setRoomUsageDatabasePortType(rud);
Orchestrator_part2.setLuminanceManagementPortType(lm);
do {
if(!timers.isEmpty()) {
WakeReason w = timers.element().reason;
// Counter on event
switch(w) {
case DAILY_WAKEUP:
dailyWakeupEventCounter++;
break;
case CLIMATE_WAKEUP:
climateControlEventCounter++;
break;
case LUMINANCE_WAKEUP:
luminanceManagementEventCounter++;
break;
}
}
res = Orchestrator_part2.wakeUp(timers);
// Counter on error
switch (res) {
case DAILY_WAKEUP_ERROR:
dailyWakeupErrorCounter++;
break;
case CLIMATE_WAKEUP_ERROR:
climateControlErrorCounter++;
break;
case LUMINANCE_WAKEUP_ERROR:
luminanceManagementErrorCounter++;
break;
}
}
while (res != Error.NO_EVENT);
}
// Print statistics
System.out.println("(3) Integration Test - Orchestrator - Report");
System.out.println("Tested functions");
printStatistics(Error.DAILY_WAKEUP_ERROR,dailyWakeupErrorCounter,dailyWakeupEventCounter);
printStatistics(Error.CLIMATE_WAKEUP_ERROR,climateControlErrorCounter,climateControlEventCounter);
printStatistics(Error.LUMINANCE_WAKEUP_ERROR,luminanceManagementErrorCounter,luminanceManagementEventCounter);
} |
32c39c63-af12-4f70-9646-903cf1727d22 | 8 | @Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
TypeRef other = (TypeRef) obj;
if (isList != other.isList) {
return false;
}
if (isMap != other.isMap) {
return false;
}
if (name == null) {
if (other.name != null) {
return false;
}
} else if (!name.equals(other.name)) {
return false;
}
return true;
} |
bb37ac00-ba68-41a2-94d7-5d63f5572715 | 4 | private void checkExpiryTime() {
double referenceTime = Double.MAX_VALUE;
LinkedList<ScheduleItem> removedRes = new LinkedList<ScheduleItem>();
Iterator<ServerReservation> iterRes = reservTable.values().iterator();
while(iterRes.hasNext()) {
ServerReservation sRes = iterRes.next();
ReservationStatus status = sRes.getReservationStatus();
// check for expiry time
if (status == ReservationStatus.NOT_COMMITTED &&
sRes.getExpiryTime() <= GridSim.clock()) {
logger.info("Reservation # " + sRes.getID() + " has not been " +
"committed and has hence been cancelled at time #" + GridSim.clock());
removeReservation(sRes); // update the profile
sRes.setStatus(ReservationStatus.CANCELLED);
expiryTable.put(sRes.getID(), sRes);
iterRes.remove();
referenceTime = Math.min(referenceTime, sRes.getStartTime());
removedRes.add(sRes);
}
}
if(removedRes.size() > 0) {
//-------------- USED FOR DEBUGGING PURPOSES ONLY -----------------
visualizer.notifyListeners(this.get_id(), ActionType.ITEM_CANCELLED, true, removedRes);
//-----------------------------------------------------------------
// performs the compression of the schedule
compressSchedule(referenceTime, false);
//---------------- USED FOR DEBUGGING PURPOSES ONLY ----------------
visualizer.notifyListeners(this.get_id(), ActionType.SCHEDULE_CHANGED, true);
//-----------------------------------------------------------------
}
} |
6473932d-abe7-405e-9669-b73e7b1566d4 | 8 | public static boolean truePropositionsIteratorDnextP(TruePropositionsIterator self) {
{ Iterator cursor = self.propositionCursor;
Proposition proposition = null;
if (cursor == null) {
return (false);
}
loop000 : for (;;) {
if (cursor.nextP()) {
proposition = ((Proposition)(cursor.value));
}
else {
{ Cons pattern = AbstractPropositionsIterator.nextEquivalentSelectionPattern(self);
if (pattern != null) {
cursor = Logic.selectPropositions(pattern).allocateIterator();
self.propositionCursor = cursor;
continue loop000;
}
else {
self.propositionCursor = null;
return (false);
}
}
}
if ((!proposition.deletedP()) &&
((((Boolean)(Logic.$REVERSEPOLARITYp$.get())).booleanValue() ? Proposition.falseP(proposition) : (Proposition.trueP(proposition) ||
Proposition.functionWithDefinedValueP(proposition))))) {
self.value = proposition;
self.truthValue = Proposition.propositionTruthValue(proposition);
return (true);
}
}
}
} |
6de346f6-9bbc-41dd-ad40-1b19c4eb7078 | 3 | @Override
public boolean onKeyDown(int key) {
if(super.onKeyDown(key)) {
return true;
}
if(key == Keyboard.KEY_TAB) {
Application.get().getHumanView().addScreen(ConsoleFactory.create());
return true;
}
else if(key == Keyboard.KEY_ESCAPE) {
Application.get().getEventManager().queueEvent(new GameStateChangeEvent(GameLogic.GameState.PAUSED));
Application.get().getHumanView().addScreen(PauseScreenFactory.create());
return true;
}
return false;
} |
316a3302-eccd-4ec5-8085-5174498bcb1e | 8 | @Override
public JobTrackerACK heartBeat(TaskTrackerReport report) {
report.printReport();
JobTrackerACK rst = new JobTrackerACK(null, null);
rst.newAddedTasks = new ArrayList<Task>();
rst.rcvTasks = new ArrayList<TaskStatus>();
while (this.taskList.size() > 0) {
synchronized (this.taskList) {
rst.newAddedTasks.add(this.taskList.get(0));
this.taskList.remove(0);
}
}
if (report != null && report.taskStatus != null && report.taskStatus.size() > 0 ) {
for (TaskStatus rcvTask : report.taskStatus) {
if (rcvTask.status == WorkStatus.FAILED || rcvTask.status == WorkStatus.SUCCESS) {
rst.rcvTasks.add(rcvTask);
}
}
}
for (Task task : rst.newAddedTasks) {
System.out.format("new task: <jid = %s, tid = %s>\n", task.getJobId(), task.getTaskId());
}
return rst;
} |
e253854c-53b0-4984-bf8d-85abfe55a1e1 | 3 | public void changeState(int option){
switch(option){
case 0:
this.isOkay = true;
break;
case 1:
this.isInjured = true;
this.isOkay = false;
break;
case 2:
this.isInjured =false;
this.isDead = true;
break;
}
} |
2306fa8c-fdde-40e1-a07d-1cd9fd364aac | 8 | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String submitButton = (String) request.getParameter("submit_btn");
int adminUserID = Integer.parseInt(request.getParameter("admin_userid"));
int targetUserID = Integer.parseInt(request.getParameter("removed_userid"));
User adminUser = User.getUserByUserID(adminUserID);
User targetUser = User.getUserByUserID(targetUserID);
if (adminUser.permission == User.IS_ADMIN && adminUser.userID != targetUserID) {
if (submitButton.equals("Remove User")) {
User.removeUser(targetUser);
} else if (submitButton.equals("Unremove User")) {
User.unremoveUser(targetUser);
} else if (submitButton.equals("Block User")) {
User.blockUser(targetUser);
} else if (submitButton.equals("Unblock User")) {
User.unblockUser(targetUser);
} else if (submitButton.equals("Promote User")) {
User.promoteUser(targetUser);
} else if (submitButton.equals("Unpromote User")) {
User.unpromoteUser(targetUser);
}
}
RequestDispatcher dispatch = request.getRequestDispatcher("admin/admin_user.jsp?keyword=" + targetUser.username);
dispatch.forward(request, response);
} |
603ca704-64dc-47f5-ad40-5837856eb6a1 | 6 | private int readString(boolean verbatim) {
read();
prepareString();
do {
// check escapes
switch (_val) {
case (char) -1:
throw new ScoreException("Unfinished string");
case '\n':
case '\r':
if (!verbatim)
throw new ScoreException("Cannot have a line break in a single-line string.");
_sb.append(_val);
break;
case '\\':
read();
_sb.append(escape(_val));
break;
default:
_sb.append(_val);
}
read();
} while (_val != '\"'); // the end of the string
read();
return TK_STRINGLITERAL;
} |
26d69dc1-de5e-46f2-a750-a95cd67a281b | 5 | public void cadastrar(Consulta consulta) throws Exception{
if(consulta.getCodMedico() == null){
throw new Exception("Medico não foi selecionado !");
}
if(consulta.getCodPaciente() == null){
throw new Exception("Paciente não foi selecionado !");
}
if(consulta.getObservacao().isEmpty()){
throw new Exception("Observação esta invalido !");
}
if(consulta.getCodProcedimento() == 0){
throw new Exception("Procedimento esta invalido !");
}
if(consulta.getData().equals(" / / ")){
throw new Exception("A data esta invalida !");
}
ConsultaDao.obterInstancia().incluir(consulta);
} |
40a2c7ca-8eff-4950-b457-ee435f9b07fe | 7 | private Solution recursiveDLS(Node node, int limit) {
closed.add(node.getState());
boolean cutoffOccured = false;
if (goalTest(node.getState())) return new Solution(node);
if (node.getDepth() == limit) return new Cutoff();
for (Node child: node.expand())
if (!closed.contains(child.getState())) {
Solution result = recursiveDLS(child, limit);
if (result instanceof Cutoff)
cutoffOccured = true;
else if (result != null)
return result;
}
if (cutoffOccured) return new Cutoff();
return null;
} |
5a058146-d668-4dfb-b555-4d7b48d75570 | 0 | public InetAddress getInetAddress() {
return addr;
} |
d9410ae4-05c6-4652-b40b-9b8c06e1a63e | 8 | @SuppressWarnings("unchecked")
private void updateShadow(Point2D mousePosition) {
if (mousePosition == null) {
getCanvas().setShadow(null);
return;
}
Board board = getBoard();
if (board.isGameOver()) {
return;
}
List<Move> moves = new LinkedList<Move>();
// Are we trying to jump?
int x = (int) Math.round(mousePosition.getX() * 2);
int y = (int) Math.round(mousePosition.getY() * 2);
boolean jump = x % 2 == 1 && y % 2 == 1;
if (jump) {
Position pos = new Position(x / 2, y / 2);
Move move = new Jump(pos);
if (move.isLegal(board)) {
getCanvas().setShadow(move);
}
return;
}
// Determine whether we're trying to place a horizontal or a vertical
// wall. Thanks to John Farrell (friendless.farrell@gmail.com), 18
// January 2007.
double rx = (mousePosition.getX() + .5) % 1;
double ry = (mousePosition.getY() + .5) % 1;
Wall wall = (ry < rx) ^ (ry < 1 - rx) ? Wall.HORIZONTAL : Wall.VERTICAL;
x = (int) Math.round(mousePosition.getX()) - 1;
y = (int) Math.round(mousePosition.getY()) - 1;
Position pos = new Position(x, y);
moves.add(new PutWall(pos, wall));
moves.add(new PutWall(pos, wall.flip()));
for (Move move : moves) {
if (move.isLegal(board)) {
getCanvas().setShadow(move);
return;
}
}
// No valid move found for the current mouse position.
getCanvas().setShadow(null);
} |
50b63477-4590-43ac-93f4-499c741ff2d3 | 5 | public static ArrayList<MeetingRoom> searchRoomByName(String name) {
try {
if(conn == null || conn.isClosed()){
conn = DatabaseConnection.getConnection();
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayList<MeetingRoom> rooms = new ArrayList<MeetingRoom>();
try {
PreparedStatement stmnt = conn.prepareStatement("SELECT * FROM MeetingRooms WHERE name LIKE ? ");
stmnt.setString(1, "%" + name + "%");
ResultSet res;
res = stmnt.executeQuery();
while(res.next()) {
meetingroom = new MeetingRoom(res.getInt("room_id"), res.getInt("floor"),res.getInt("seats_amount"), res.getString("name"));
rooms.add(meetingroom);
}
}
catch(SQLException e){
e.printStackTrace();
}
return rooms;
} |
268c160c-ddee-4ad9-ae6a-8ecb92489903 | 5 | public static void main(String[] args) throws InterruptedException {
if (args.length != 4) {
exitWithError();
}
String dataStructure = args[0];
int nrThreads = Integer.parseInt(args[1]);
if (nrThreads < 1) {
exitWithError();
}
int nrItems = Integer.parseInt(args[2]);
if (nrItems < 1) {
exitWithError();
}
if (nrItems % nrThreads != 0) {
System.out.println("nrItems should be divisible by nrThreads");
System.exit(1);
}
int workTime = Integer.parseInt(args[3]);
if (workTime < 0) {
exitWithError();
}
long seed = computeSeed(nrThreads, nrItems, workTime);
performWork(dataStructure, nrThreads, nrItems, workTime, seed);
} |
931e3edb-40a1-48bf-833f-825f7eb6b310 | 2 | public void run() {
try {
while (true) {
TimeUnit.MILLISECONDS.sleep(100);
System.out.println(Thread.currentThread() + " " + this);
}
} catch (InterruptedException e) {
System.out.println("sleep() interrupted");
}
} |
345350c5-fc98-44ee-be95-8a3febdc10b9 | 8 | private boolean handleTraverseHandle(KeyEvent e) {
EditPart focus = getCurrentViewer().getFocusEditPart();
if (focus.getSelected() == EditPart.SELECTED_NONE)
return false;
getCurrentViewer().reveal(focus);
AccessibleHandleProvider provider;
provider = (AccessibleHandleProvider) focus
.getAdapter(AccessibleHandleProvider.class);
if (provider == null
|| provider.getAccessibleHandleLocations().isEmpty())
return false;
/*
* At this point, a handle provider with 1 or more handles has been
* obtained
*/
setState(STATE_TRAVERSE_HANDLE);
List locations = provider.getAccessibleHandleLocations();
// Goto next index, wrapping if necessary
if (e.character == '.')
handleIndex = (++handleIndex) % locations.size();
else
handleIndex = (--handleIndex + locations.size()) % locations.size();
if (getLastHandleProvider() != focus) {
handleIndex = 0;
setLastHandleProvider(focus);
}
Point loc = (Point) locations.get(handleIndex);
Point current = new Point(getCurrentViewer().getControl().toControl(
Display.getCurrent().getCursorLocation()));
if (current.equals(loc)) {
// The cursor is already at the location that it is to be moved to.
// So, we
// move to the next handle instead. If there are no more handles,
// then we
// cancel the drag.
if (locations.size() > 1)
if (e.character == '.')
handleIndex = (++handleIndex) % locations.size();
else
handleIndex = (--handleIndex + locations.size())
% locations.size();
else {
placeMouseInViewer(loc.getTranslated(6, 6));
return false;
}
}
placeMouseInViewer((Point) locations.get(handleIndex));
return true;
} |
d504dd1f-6a45-4dbb-afd4-66a4e62b6875 | 5 | private void buildMapActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buildMapActionPerformed
int x,y;
try{
x = Integer.valueOf(this.xField.getText());
y = Integer.valueOf(this.yField.getText());
} catch (Exception e){
this.warningsLabel.setText("Must enter integers");
this.xField.setText("");
this.yField.setText("");
return;
}
if(x <= 0 || x > 5 || y <= 0 || y > 5){
this.warningsLabel.setText("Must enter in bounds [1,5]");
this.xField.setText("");
this.yField.setText("");
return;
}
this.canvas.clean();
MyMapBuilder b = new MyMapBuilder();
b.setSize(x, y);
Map<MyHex> m = b.buildMap();
GeometricAdapter geo = new GeometricAdapter(m);
Metric metric = new Metric(GeoElements.OfHexagon.NotableSegments.DIAMETER, 50);
geo.setMetric(metric);
this.canvas.setSize((int)geo.sizeX(), (int)geo.sizeY()+10);
this.canvas.paintHex(geo, m);
} |
0bd7a956-635b-414d-863f-3c67e5f0720d | 7 | public static Cons cppGetConstructorDefinitions(Stella_Class renamed_Class) {
{ Cons constructordefs = Stella.NIL;
{ Slot slot = null;
Iterator iter000 = renamed_Class.classSlots();
Cons collect000 = null;
while (iter000.nextP()) {
slot = ((Slot)(iter000.value));
if ((!slot.slotMarkedP) &&
((slot.primaryType() == Stella.SGT_STELLA_METHOD_SLOT) &&
(Slot.localSlotP(slot, renamed_Class) &&
MethodSlot.cppConstructorP(((MethodSlot)(slot)))))) {
if (collect000 == null) {
{
collect000 = Cons.cons(MethodSlot.cppYieldConstructorSignatureTree(((MethodSlot)(slot))), Stella.NIL);
if (constructordefs == Stella.NIL) {
constructordefs = collect000;
}
else {
Cons.addConsToEndOfConsList(constructordefs, collect000);
}
}
}
else {
{
collect000.rest = Cons.cons(MethodSlot.cppYieldConstructorSignatureTree(((MethodSlot)(slot))), Stella.NIL);
collect000 = collect000.rest;
}
}
}
}
}
return (constructordefs);
}
} |
2156ad31-ad1d-49b9-a2da-918177bc2b4c | 1 | public void checkStock(){
if (this.stock<this.minS){
this.inOrderCost(hitungOrderCost(this.maxS-this.stock));
this.reCountCost();
this.stock=this.maxS;
}
} |
8d8a3114-8b53-4fa1-bf61-2fbc084d143e | 7 | public <T> int updateDB(String query, ArrayList<T> sqlParam){
PreparedStatement ps = null;
int rs = 0;
try{
ps = conn.prepareStatement(query);
int i = 1;
for (T a : sqlParam){
//System.out.println(a.getClass());
if (a.getClass() == String.class){
ps.setString(i, (String)a);
//System.out.println(String.format("I'm a String! %d - %s", i, (String) a));
}else if(a.getClass() == Integer.class){
ps.setInt(i, (Integer)a);
//System.out.println(String.format("I'm an Integer! %d - %d", i, (Integer) a));
}else if(a.getClass() == Double.class){
ps.setDouble(i, (Double)a);
//System.out.println(String.format("I'm a Double! %d - %f", i, (Double) a));
}else if (a.getClass() == Timestamp.class){
ps.setTimestamp(i, (Timestamp)a);
//System.out.println(String.format("I'm a DateTime! %d - %s", i, a.toString()));
}else if (a.getClass() == Long.class){
ps.setLong(i, (Long)a);
//System.out.println(String.format("I'm a DateTime! %d - %s", i, a.toString()));
}
i++;
}
rs = ps.executeUpdate();
}catch (SQLException e){
e.printStackTrace();
return 0;
}
return rs;
} |
c9cd8b64-7db3-451a-a099-2f38596daf06 | 2 | private String readResource(String filename) {
StringBuilder builder = new StringBuilder();
try {
FileInputStream stream = new FileInputStream(new File(resPath + filename));
try {
Reader reader = new BufferedReader(new InputStreamReader(stream));
char[] buffer = new char[8192];
int read;
while ((read = reader.read(buffer, 0, buffer.length)) > 0) {
builder.append(buffer, 0, read);
}
} finally {
stream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return builder.toString();
} |
c2a4911c-6021-4255-ab08-b46e551cc5a1 | 2 | public boolean isInReferrerString(String referrerString) {
for (String alias : aliases) {
if (referrerString.toLowerCase().indexOf(alias.toLowerCase()) != -1)
return true;
}
return false;
} |
29d6bd8a-525a-45bc-9646-94b73f14aaa6 | 8 | public boolean stem() {
int v_1;
int v_2;
int v_3;
int v_4;
// (, line 133
// do, line 134
v_1 = cursor;
lab0: do {
// call prelude, line 134
if (!r_prelude())
{
break lab0;
}
} while (false);
cursor = v_1;
// do, line 135
v_2 = cursor;
lab1: do {
// call mark_regions, line 135
if (!r_mark_regions())
{
break lab1;
}
} while (false);
cursor = v_2;
// backwards, line 136
limit_backward = cursor; cursor = limit;
// do, line 137
v_3 = limit - cursor;
lab2: do {
// call standard_suffix, line 137
if (!r_standard_suffix())
{
break lab2;
}
} while (false);
cursor = limit - v_3;
cursor = limit_backward; // do, line 138
v_4 = cursor;
lab3: do {
// call postlude, line 138
if (!r_postlude())
{
break lab3;
}
} while (false);
cursor = v_4;
return true;
} |
b7460e14-aaca-4b70-9c79-9605185f1151 | 7 | void setPreferences(Preferences pref) {
cacheCheckBox.setSelected(ConnectionManager.sharedInstance().isCachingAllowed());
dayField.setValue(HistoryManager.sharedInstance().getDays());
if (pref == null)
return;
connectTimeoutField.setValue(pref.getInt("Connect Timeout", 5));
readTimeoutField.setValue(pref.getInt("Read Timeout", 30));
String s = pref.get("Proxy Address", null);
if (s != null) {
int i = pref.getInt("Proxy Port", -1);
if (i != -1) {
setUseProxy(true);
proxyPortField.setValue(i);
proxyAddressField.setText(s);
s = pref.get("Proxy Username", null);
if (s != null)
usernameField.setText(s);
s = pref.get("Proxy Password", null);
if (s != null)
passwordField.setText(s);
}
}
else {
setUseProxy(false);
}
s = Initializer.sharedInstance().getSystemProperty(HOME_PAGE);
setHome(s != null ? s : modeler.navigator.getHomePage());
s = pref.get("Start From", null);
if (s != null)
setStartPageType(s);
} |
d8958967-1989-469e-80f0-c1dcd2558b70 | 0 | public Field getField()
{
return field;
} |
0f4be775-1442-4dbc-93a1-29d354e1fe36 | 3 | private int getNameIDFromUser(String prompt){
while(true){
try {
String Name = getUserInput(prompt);
if (Name.equals("NONE")) return 0;
return RunFileGame.getPlayerIDFromName(Name);
} catch (WrongNameException e) {
System.out.println("FUCK OFF THATS NOT A NAME");
}
}
} |
6ccb41fe-0b57-43ef-a584-7ee15e702e99 | 1 | public void send(Object data)
{
if(!connection.isConnected())
return;
connection.sendTCP(data);
} |
809e52ae-76a3-4f8b-b707-d41ea9fb0c88 | 7 | private void jj_rescan_token() {
jj_rescan = true;
for (int i = 0; i < 3; i++) {
try {
JJCalls p = jj_2_rtns[i];
do {
if (p.gen > jj_gen) {
jj_la = p.arg; jj_lastpos = jj_scanpos = p.first;
switch (i) {
case 0: jj_3_1(); break;
case 1: jj_3_2(); break;
case 2: jj_3_3(); break;
}
}
p = p.next;
} while (p != null);
} catch(LookaheadSuccess ls) { }
}
jj_rescan = false;
} |
a4b55349-4321-44fe-a676-799269f79fa1 | 4 | private void applyVocation(Background v, Actor actor) {
///I.say("Applying vocation: "+v) ;
for (Skill s : v.baseSkills.keySet()) {
final int level = v.baseSkills.get(s) ;
actor.traits.raiseLevel(s, level + (Rand.num() * 5)) ;
}
for (Trait t : v.traitChances.keySet()) {
float chance = v.traitChances.get(t) ;
while (Rand.index(10) < Math.abs(chance) * 10) {
actor.traits.incLevel(t, chance > 0 ? 0.5f : -0.5f) ;
chance /= 2 ;
}
actor.traits.incLevel(t, chance * Rand.num()) ;
}
} |
21f08f58-bd22-4ca7-9441-0c0e556dd41a | 2 | @Override
protected void setPanelPerson(Contestant c, boolean newContestant) {
super.setPanelPerson(c, newContestant);
btnSetStatus.setEnabled(GameData.getCurrentGame().isSeasonStarted());
if (newContestant || c == null) {
// we don't want any rows selected
ListSelectionModel m = table.getSelectionModel();
m.clearSelection();
return;
}
tableModel.setRowSelect(c);
} |
6c59ec82-6570-400a-9501-c15069b3913f | 8 | public boolean containsValue( Object val ) {
byte[] states = _states;
V[] vals = _values;
// special case null values so that we don't have to
// perform null checks before every call to equals()
if ( null == val ) {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL && null == vals[i] ) {
return true;
}
}
} else {
for ( int i = vals.length; i-- > 0; ) {
if ( states[i] == FULL &&
( val == vals[i] || val.equals( vals[i] ) ) ) {
return true;
}
}
} // end of else
return false;
} |
613d9719-d99f-4b0a-8dbc-2889379d0e14 | 7 | @SuppressWarnings("unused")
@Override
/** When you click on a specific button it goes to a specific tutorial
* @param arg0 the action event which triggers actionPerformed and contains the information
*/
public void actionPerformed(ActionEvent arg0)
{
String id = "";
if (arg0.getSource() == rules)
{
id += "p";
}
if (arg0.getSource() == territories)
{
id += "c";
}
if (arg0.getSource() == endGame)
{
id += "s";
}
if (arg0.getSource() == capturing)
{
id += "i";
}
if (arg0.getSource() == generalPlay)
{
id += "u";
}
String blank;
if (id.equals(""))
{
// add code to start the game, or to go back to the start menu. I lean more towards the
// start menu.
JOptionPane.showMessageDialog(null, "Okay, time to play, just close this window and select your game mode to get started.");
}
setVisible(true);
try
{
Desktop.getDesktop().browse(URI.create(map.get(id)));
}
catch (IOException e)
{
e.printStackTrace();
}
} |
2af65e98-ba94-466a-9b56-9609f7a1b2de | 8 | public void getWarden() {
r = random.nextInt(y);
warden = derp.get(r);
locwar = new Location(warden.getPlayer().getWorld(), -140, 69, -110);
cell1 = new Location(warden.getPlayer().getWorld(), -114, 68, -109);
cell2 = new Location(warden.getPlayer().getWorld(), -116, 68, -109);
Bukkit.broadcastMessage(ChatColor.BLUE + "" + ChatColor.BOLD + warden.getName() + " is the Warden!");
((Player) warden).teleport(locwar);
for(OfflinePlayer players : team.getPlayers()){
int c = random.nextInt(2);
if(c == 0 && players != warden) ((Player)players).teleport(cell1);
if(c == 1 && players != warden) ((Player)players).teleport(cell2);
if(c != 1 && c != 0 && players != warden) ((Player)players).teleport(cell2);
}
} |
1b4522d2-d1f5-4fd4-9695-43eb311cee08 | 0 | public String getEvento()
{
return tipoEvento.getText();
} |
82c746b4-de5f-447e-912e-b4ee3410bbb7 | 3 | private void modifySuperclass(CtClass orgclass)
throws CannotCompileException, NotFoundException
{
CtClass superclazz;
for (;; orgclass = superclazz) {
superclazz = orgclass.getSuperclass();
if (superclazz == null)
break;
try {
superclazz.getDeclaredConstructor(null);
break; // the constructor with no arguments is found.
}
catch (NotFoundException e) {
}
superclazz.addConstructor(
CtNewConstructor.defaultConstructor(superclazz));
}
} |
716f60f7-d3c6-4c77-86c1-6640f1d18e82 | 6 | private void validate() throws RrdException {
if(!isValidConsolFun(consolFun)) {
throw new RrdException("Invalid consolidation function specified: " + consolFun);
}
if(Double.isNaN(xff) || xff < 0.0 || xff >= 1.0) {
throw new RrdException("Invalid xff, must be >= 0 and < 1: " + xff);
}
if(steps <= 0 || rows <= 0) {
throw new RrdException("Invalid steps/rows number: " + steps + "/" + rows);
}
} |
a2e37e3e-b74d-4dec-acc5-e2432b538db0 | 6 | public final double grad(int par1, double par2, double par4, double par6)
{
int var8 = par1 & 15;
double var9 = var8 < 8 ? par2 : par4;
double var11 = var8 < 4 ? par4 : (var8 != 12 && var8 != 14 ? par6 : par2);
return ((var8 & 1) == 0 ? var9 : -var9) + ((var8 & 2) == 0 ? var11 : -var11);
} |
1bd288f8-bbf6-4351-9139-7e9fb6c1ab8c | 3 | public void deletarLista(List<T> ts) throws org.hibernate.exception.ConstraintViolationException, ValidacaoException {
try {
transacao = session.beginTransaction();
session.clear();
session.flush();
for (T t : ts) {
session.delete(t);
}
transacao.commit();
} catch (org.hibernate.exception.ConstraintViolationException ex) {
transacao.rollback();
throw new ConstraintViolationException(ex.getMessage(), ex.getSQLException(), ex.getConstraintName());
} catch (HibernateException e) {
transacao.rollback();
throw new ValidacaoException(e.getMessage());
}
} |
445afad1-f32c-4603-9488-810ad5f16d79 | 7 | public List<HipchatUser> getStandupUsers()
{
List<HipchatUser> remaining_users = new ArrayList<HipchatUser>();
List<String> user_names = current_room.getConnectedUsers();
List<HipchatUser> users = new ArrayList<HipchatUser>();
for ( String user_name : user_names )
{
HipchatUser user = hippy_bot.findUser(user_name.substring(user_name.indexOf("/")+1));
if ( user != null )
users.add(user);
}
for ( HipchatUser user : users )
{
if ( !user.getStatus().equals("offline") && !user.getName().equals(hippy_bot.nickname()) &&
!bot_data.blacklist.contains( user.getMentionName() ) && !users_early_standup.keySet().contains(user.getMentionName()) )
{
remaining_users.add(user);
}
}
return remaining_users;
} |
ad77d9af-d8ec-4b68-a5da-0e199ce1387c | 3 | public void visitInitStmt(final InitStmt stmt) {
print("INIT");
final LocalExpr[] t = stmt.targets();
if (t != null) {
for (int i = 0; i < t.length; i++) {
if (t[i] != null) {
print(" ");
t[i].visit(this);
}
}
}
println();
} |
adf8ebcb-a255-49b8-b1e3-aaaa5dd9e063 | 6 | public void DeleteVulnerabilityFiles(DatabaseAccess JavaDBAccess, String TargetPHPFileSelectedComboBox) {
int TARGET_PHP_FILES_ID = 0;
PreparedStatement ps = null;
Connection conn = null;
try {
if ((conn = JavaDBAccess.setConn()) != null) {
System.out.println("Connected to database " + JavaDBAccess.getDatabaseName());
} else {
throw new Exception("Not connected to database " + JavaDBAccess.getDatabaseName());
}
conn.setAutoCommit(false);
// Start a transaction by inserting a record in the TARGET_PHP_FILES table
ps = conn.prepareStatement("SELECT ID FROM TARGET_PHP_FILES WHERE PATH = ?");
ps.setString(1, TargetPHPFileSelectedComboBox);
ResultSet rs = ps.executeQuery();
rs.next();
TARGET_PHP_FILES_ID = rs.getInt(1);
rs.close();
// Start a transaction by inserting a record in the TARGET_PHP_FILES table
ps = conn.prepareStatement("SELECT ID FROM RESULTS WHERE TARGET_PHP_FILE = ?");
ps.setInt(1, TARGET_PHP_FILES_ID);
rs = ps.executeQuery();
while (rs.next()) {
// Open matches log file.
try {
boolean success = (new File(TargetPHPFileSelectedComboBox + "_" + rs.getRow() + ".php")).delete();
if (!success) {
System.out.println("Expected file " + TargetPHPFileSelectedComboBox + "_" + rs.getRow() + ".php" + " does not exist!");
}
} catch (Exception e) {
System.out.println("Unable to open matches Web Page log file.");
}
}
rs.close();
conn.commit();
conn.close();
} catch (Throwable e) {
System.out.println("Errors in DeleteVulnerabilityFiles!");
System.out.println("exception thrown:");
if (e instanceof SQLException) {
JavaDBAccess.printSQLError((SQLException) e);
} else {
e.printStackTrace();
}
}
} |
9c61a48f-1053-4363-a393-0ebc76ac79b3 | 6 | @Override
public void actionPerformed(ActionEvent e) {
//System.out.println("PasteAction");
OutlinerCellRendererImpl textArea = null;
boolean isIconFocused = true;
Component c = (Component) e.getSource();
if (c instanceof OutlineButton) {
textArea = ((OutlineButton) c).renderer;
} else if (c instanceof OutlineLineNumber) {
textArea = ((OutlineLineNumber) c).renderer;
} else if (c instanceof OutlineCommentIndicator) {
textArea = ((OutlineCommentIndicator) c).renderer;
} else if (c instanceof OutlinerCellRendererImpl) {
textArea = (OutlinerCellRendererImpl) c;
isIconFocused = false;
}
// Shorthand
Node node = textArea.node;
JoeTree tree = node.getTree();
OutlineLayoutManager layout = tree.getDocument().panel.layout;
//System.out.println(e.getModifiers());
switch (e.getModifiers()) {
case 2:
if (isIconFocused) {
paste(textArea, tree, layout);
} else {
pasteText(textArea, tree, layout);
}
break;
}
} |
ad6713d1-eb43-48bd-bae3-3728a46053b8 | 9 | int insertKeyRehash(float val, int index, int hash, byte state) {
// compute the double hash
final int length = _set.length;
int probe = 1 + (hash % (length - 2));
final int loopIndex = index;
int firstRemoved = -1;
/**
* Look until FREE slot or we start to loop
*/
do {
// Identify first removed slot
if (state == REMOVED && firstRemoved == -1)
firstRemoved = index;
index -= probe;
if (index < 0) {
index += length;
}
state = _states[index];
// A FREE slot stops the search
if (state == FREE) {
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
} else {
consumeFreeSlot = true;
insertKeyAt(index, val);
return index;
}
}
if (state == FULL && _set[index] == val) {
return -index - 1;
}
// Detect loop
} while (index != loopIndex);
// We inspected all reachable slots and did not find a FREE one
// If we found a REMOVED slot we return the first one found
if (firstRemoved != -1) {
insertKeyAt(firstRemoved, val);
return firstRemoved;
}
// Can a resizing strategy be found that resizes the set?
throw new IllegalStateException("No free or removed slots available. Key set full?!!");
} |
313b5836-46e9-430f-b0f7-f1879cf11fb2 | 0 | @Override
public void actionPerformed(ActionEvent e) {
importOutlinerDocument(getProtocol());
} |
071163ac-67fc-49bf-a731-238b00273f40 | 5 | public static ArrayList<ChatPlayer> getPlayersListeningToChannel(String channel) {
ArrayList<ChatPlayer> plays = new ArrayList<ChatPlayer>();
for (ChatPlayer play : players) {
boolean forced = Bukkit.getPlayer(play.name) != null && MCNSAChat3.permissions.has(Bukkit.getPlayer(play.name), "mcnsachat3.forcelisten." + channel.toLowerCase());
if (play.listening.contains(channel.toLowerCase()) || play.modes.contains(ChatPlayer.Mode.SEEALL) || forced)
plays.add(play);
}
return plays;
} |
b25d878c-782d-46ff-9174-8c82e3332fd5 | 0 | public synchronized void terminate() {
enabled = false;
active = false;
} |
6d430c03-500e-4f01-b411-c3870f6316e8 | 7 | protected AttrTypes testsPerClassType(int classType, EstTypes estTypes) {
// in none of the estimators yet is the estimation depending on the class type
// since this could change the basic structure taken from checkclassifiers is kept here
// test A: simple test - if can estimate
AttrTypes attrTypes = new AttrTypes();
AttrTypes at = new AttrTypes(Attribute.NOMINAL);
attrTypes.nominal = canEstimate(at, estTypes.supervised, classType)[0];
at = new AttrTypes(Attribute.NUMERIC);
attrTypes.numeric = canEstimate(at, estTypes.supervised, classType)[0];
attrTypes.string = false;
attrTypes.date = false;
attrTypes.relational = false;
// if (!multiInstance)
// PRel = canEstimate(false, false, false, false, true, classType)[0];
// else
// PRel = false;
// one of the attribute types succeeded
if (attrTypes.oneIsSet()) {
Vector attributesSet = attrTypes.getVectorOfAttrTypes();
// make tests for each attribute
for (int i = 0; i < attributesSet.size(); i++) {
AttrTypes workAttrTypes = new AttrTypes(((Integer) attributesSet.elementAt(i)).intValue());
// test B: weights change estimate or not
if (estTypes.weighted)
instanceWeights(workAttrTypes, classType);
if (classType == Attribute.NOMINAL) {
int numClasses = 4;
canHandleNClasses(workAttrTypes, numClasses);
}
// tests with class not the last attribute and the attribute not the first
// if (!multiInstance) {
int numAtt = 4;
canHandleClassAsNthAttribute(workAttrTypes, numAtt, 0, classType, 1);
//TODOTODOcanHandleAttrAsNthAttribute(workAttrTypes, numAtt, 2, classType);
//}
canHandleZeroTraining(workAttrTypes, classType);
boolean handleMissingAttributes = canHandleMissing(workAttrTypes,
classType, true, false, 20)[0];
if (handleMissingAttributes)
canHandleMissing(workAttrTypes, classType, true, false, 100);
boolean handleMissingClass = canHandleMissing(workAttrTypes,
classType,
false, true, 20)[0];
if (handleMissingClass)
canHandleMissing(workAttrTypes, classType, false, true, 100);
correctBuildInitialisation(workAttrTypes, classType);
datasetIntegrity(workAttrTypes, classType,
handleMissingAttributes, handleMissingClass);
if (estTypes.incremental)
incrementingEquality(workAttrTypes, classType);
}
}
return attrTypes;
} |
4cba13fe-33a6-4a9a-a6f5-cb7b3d5ac4c0 | 2 | public static Vector3f parseDirection(String data) {
String[] lines = data.split("\n");
for (String line : lines) {
String[] parts = line.split(":", 2);
if (parts[0].equals("d")) {
return ParseVector3f(parts[1]);
}
}
return null;
} |
01489a59-6bf5-40fb-aca1-c20badb86e73 | 5 | @Override
public void stopService() {
try {
deregisterFromServer();
} catch (ConnectionException ex) {
LOG.warning("Server could not be reached for deregistration.");
}
disconnectFromServer();
try {
if (serverSocket != null) {
serverSocket.stopService();
}
} catch (Exception ex) {
// error closing some resource, ignore
}
try {
if (sdd != null) {
sdd.stopService();
}
} catch (Exception ex) {
// error closing some resource, ignore
}
LOG.info("Client has been stopped.");
} |
1fa566ee-cf6c-4114-b751-3f3b6448dd3e | 2 | public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String name = req.getParameter("name");
User user;
try {
// First try to find if the user exists
user = UserDAO.find(name);
if (user != null) {
HttpSession session = req.getSession(true);
session.setAttribute("currentSessionUser",user);
res.sendRedirect("/cse135");
} else {
String error = "The provided name " + name + " is not known.";
req.setAttribute("error", error);
req.getRequestDispatcher("login.jsp").forward(req, res);
}
} catch (SQLException e) {
e.printStackTrace();
// If no user found of the given name then redirect to login page with error shown
String error = "The provided name " + name + " is not known.";
req.setAttribute("error", error);
req.getRequestDispatcher("login.jsp").forward(req, res);
}
} |
08ac228f-5876-4668-8a2f-d3fa1cda99ef | 0 | public String [] getDestTermid() {
return DestTermid;
} |
85f510db-b3bb-4f0d-9d26-a6bbebe03299 | 0 | public ArrayList<ClientContact> getClientContacts() {
return mClientContacts;
} |
bf36d0f0-ab13-4400-a46b-d7cab30129a7 | 0 | @Test
public void testGetDictionary() {
assertTrue(_dictionary.getDictionary().size() > 0);
} |
cd15b079-2974-4459-99eb-b2851be339f0 | 2 | public void deleteByPerformer(String sPerformer, Long epochTime) {
EntityManager em = PersistenceManager.createEntityManager();
try {
em.getTransaction().begin();
List<Openchatroomsmessage> ochrms = em.createNamedQuery("Openchatroomsmessage.GetByUserAndTime", Openchatroomsmessage.class)
.setParameter("u", sPerformer)
.setParameter("t", epochTime)
.getResultList();
for (Openchatroomsmessage openchatroomsmessage : ochrms) {
em.remove(openchatroomsmessage);
em.getTransaction().commit();
em.getTransaction().begin();
}
em.getTransaction().commit();
} finally {
if (em.getTransaction().isActive())
em.getTransaction().rollback();
em.close();
}
} |
faad5877-c5b6-4f1a-b510-b18b70ccce81 | 9 | @Override
public boolean writeOperation(SocketChannel s, ByteBuffer buffer) throws IOException {
buffer.clear();
Main.state = ServerState.SYNCHRONIZING;
if(ido != null){
buffer.put(HexConverter.toByte(Main.ID));
buffer.putInt(514);
buffer.put(HexConverter.toByte(getJobID()));
buffer.put(Protocol.SYNC_LOCAL_INDEX.getValue());
buffer.put(command);
buffer.put(MetaDataComposer.decompose(ido));
buffer.put(LAST_INDEX);
buffer.rewind();
while(buffer.hasRemaining())
s.write(buffer);
buffer.clear();
setFinished(true);
Main.state = ServerState.IDLE;
buffer.clear();
return true;
}else{
if(localIndexCopy.isEmpty()){
setFinished(true);
Main.state = ServerState.IDLE;
return true;
}
buffer.put(HexConverter.toByte(Main.ID));
buffer.putInt(8176);
buffer.put(HexConverter.toByte(getJobID()));
buffer.put(Protocol.SYNC_LOCAL_INDEX.getValue());
int counter = 15;
while(counter > 0){
buffer.put(command);
buffer.put(MetaDataComposer.decompose(localIndexCopy.get(outerIndex).get(innerIndex)));
if(innerIndex+1 >= localIndexCopy.get(outerIndex).size()){
innerIndex = 0;
outerIndex++;
}else{
innerIndex++;
}
if(outerIndex == localIndexCopy.size()){
buffer.put(LAST_INDEX);
setFinished(true);
Main.state = ServerState.IDLE;
break;
}
counter--;
if(counter == 0){
buffer.put(LAST_INDEX);
}else{
buffer.put(NOT_LAST_INDEX);
}
}
buffer.rewind();
while(buffer.hasRemaining())
s.write(buffer);
buffer.clear();
if(isFinished())
return true;
else
return false;
}
} |
b04c2a9a-12ee-4524-935c-070d8c1b1694 | 5 | public static boolean inModalState() {
for (Window window : Window.getWindows()) {
if (window instanceof Dialog) {
Dialog dialog = (Dialog) window;
if (dialog.isShowing()) {
ModalityType type = dialog.getModalityType();
if (type == ModalityType.APPLICATION_MODAL || type == ModalityType.TOOLKIT_MODAL) {
return true;
}
}
}
}
return false;
} |
d45c0949-89e9-42b1-be97-0ec87016886e | 6 | private void executeAction(String action){
switch(action.toLowerCase()){
case "turnleft":
turnLeft();
break;
case "turnright":
turnRight();
break;
case "moveforward":
moveForward();
break;
case "movebackwards":
moveBackwards();
break;
case "harvestcolor":
harvestColor();
break;
case "depositcolor":
depositColor();
break;
default:
//ERROR accion invalida
break;
}
} |
020261d2-e069-40fe-b532-effc45122408 | 4 | public void run() {
threadStarted();
while (!isInterrupted()) {
Runnable task = null;
try {
task = getTask();
}
catch (InterruptedException ex) { }
if (task == null) {
break;
}
try {
task.run();
}
catch (Throwable t) {
uncaughtException(this, t);
}
}
threadStopped();
} |
455887ec-cefb-4708-97f4-8dcf7ba6fc8a | 0 | public void setAltitude(double altitude)
{
this.altitude = altitude;
} |
9a9c6aa2-e6fb-4644-84e7-dedd17089b16 | 1 | public void setWindowTitle() {
int s = this.playersTurn.time;
String time = String.format("%02d:%02d:%02d", s/3600, (s%3600)/60, (s%60));
this.window.setTitle(this.isActive ? "Chess: " + this.playersTurn.getName() + "'s turn (" + time + ")" : "Game ended");
} |
f61552af-09e0-43d5-b2e2-410f9be3570a | 9 | public static void main(String[] args)
{
if (args.length > 0)
{
if (args[0].equals("read"))
{
try{
map = MMStore.readMap(mapFile);
//System.out.println("Read in map of size: " + map.totalSize());
System.out.println("Read in map of size: " + map.size());
Iterator iter = map.keySet().iterator();
while(iter.hasNext())
{
Object key = iter.next();
System.out.println("[" + key + "]-->["
+ map.get(key) + "]");
}
} catch (Exception e) {
System.err.println("Caught exception: " + e.toString());
}
System.exit(0);
}
if (args[0].equals("put") && args.length > 2)
{
System.out.println("Reading hashtable from file: " + mapFile);
try{
map = MMStore.readMap(mapFile);
//readMap();
} catch (FileNotFoundException e)
{
System.out.println("File not found, will create new file.");
map = new MMStore(mapFile);
}
catch (Exception e) {
System.err.println("Caught exception: " + e.toString());
System.exit(1);
}
System.out.println("Putting [" + args[1]
+ "]-->[" + args[2] +"]");
map.put(args[1], args[2]);
try{
map.writeMap();
System.out.println("Map has " + map.size() + " entries");
} catch (IOException e) {
System.err.println("Caught exception: " + e.toString());
}
}
else
{
System.out.println("Must pass 'name' 'value' pair to put");
}
}
else
{
System.out.println(
"Usage: \tSerializingTest put <key> <val> \n" +
"\t SerializingTest read");
}
} |
5fc01cef-f2e4-49bd-b60a-35de3cf2cbce | 7 | @Override
public String getDescription(Hero hero) {
long duration = (Integer) SkillConfigManager.getSetting(hero.getHeroClass(), this, Setting.DURATION.node(), 60000);
boolean cancels = (boolean) SkillConfigManager.getSetting(hero.getHeroClass(), this, "AttackCancels", true);
String base = String.format("Turn water to ice as you walk for %s seconds.", duration/1000D);
String dmgAdd = cancels ? base : base.concat("Damage removes this buff.");
StringBuilder description = new StringBuilder( dmgAdd );
//Additional descriptive-ness of skill settings
int initCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN.node(), 0, false);
int redCD = SkillConfigManager.getUseSetting(hero, this, Setting.COOLDOWN_REDUCE.node(), 0, false) * hero.getSkillLevel(this);
int CD = (initCD - redCD) / 1000;
if (CD > 0) {
description.append( " CD:"+ CD + "s" );
}
int initM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA.node(), 0, false);
int redM = SkillConfigManager.getUseSetting(hero, this, Setting.MANA_REDUCE.node(), 0, false)* hero.getSkillLevel(this);
int manaUse = initM - redM;
if (manaUse > 0) {
description.append(" M:"+manaUse);
}
int initHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST, 0, false);
int redHP = SkillConfigManager.getUseSetting(hero, this, Setting.HEALTH_COST_REDUCE, 0, true) * hero.getSkillLevel(this);
int HPCost = initHP - redHP;
if (HPCost > 0) {
description.append(" HP:"+HPCost);
}
int initF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA.node(), 0, false);
int redF = SkillConfigManager.getUseSetting(hero, this, Setting.STAMINA_REDUCE.node(), 0, false) * hero.getSkillLevel(this);
int foodCost = initF - redF;
if (foodCost > 0) {
description.append(" FP:"+foodCost);
}
int delay = SkillConfigManager.getUseSetting(hero, this, Setting.DELAY.node(), 0, false) / 1000;
if (delay > 0) {
description.append(" W:"+delay);
}
int exp = SkillConfigManager.getUseSetting(hero, this, Setting.EXP.node(), 0, false);
if (exp > 0) {
description.append(" XP:"+exp);
}
return description.toString();
} |
c912c6f0-fdb6-43b3-9fe8-5736a6f1c729 | 1 | @Override
public void updateAudioObject(int objectId, double volume, double pitch,
boolean shouldLoop) {
if (objectId == 0) {
return;
}
AudioObject object = objects.get(objectId);
object.volume = volume;
object.pitch = pitch;
object.loop = shouldLoop;
} |
33a27f39-2cd0-49dc-9bd5-f0f8fd8f0004 | 2 | public static ArrayList<String> load(String filename)
{
Scanner file_scanner = null;
ArrayList<String> stringArray = new ArrayList<String>();
try {
file_scanner = new Scanner(new File(filename)); //Connection to the file using the Scanner object
} catch (FileNotFoundException ex) {
System.out.println("Could not find the file to load from! Returning null.");
ex.printStackTrace();
return null; //If something goes wrong the method returns null
}
while (file_scanner.hasNextLine()) { //File found. Reading one line.
stringArray.add(file_scanner.nextLine()); //Reading in a single line and saving in the ArrayList
}
file_scanner.close(); //Closing the file
return stringArray; //returning the arraylist
} |
48f69674-2052-446f-93be-f8be84eba095 | 8 | public static void main(String args[]) {
FopsDB db = new FopsDB();
Gson gson = db.getGson();
GsonBuilder builder = new GsonBuilder();
List<Rule> rules = new ArrayList<Rule>();
List<Staff> faculty = new ArrayList<Staff>();
/* Construct Rules */
status("Constructing rules");
rules.add(new MinimumYearsServiceRule(3));
rules.add(new NumberRepresentativesRule(1));
rules.add(new NumberAtLargeMembersRule(2));
rules.add(new MinimumRankRule(Rank.ASSOCIATE_PROFESSOR));
/* Add Committees */
status("Adding committees");
String com1 = "Test Committee One";
String com2 = "Test Committee Two";
db.addCommittee(new Committee(com1,
CommitteeType.UNIVERSITY, rules));
db.addCommittee(new Committee(com2,
CommitteeType.AD_HOC, null));
/* Construct Staff */
status("Constructing staff");
faculty.add(new Staff("John Doe", Gender.MALE,
College.BUSINESS, Discipline.LATIN,
Rank.PROFESSOR, new MonthYear(9, 1985), true));
faculty.add(new Staff("Jane Doe", Gender.FEMALE,
College.ARTS_AND_SCIENCES,
Discipline.BIOLOGY, Rank.INSTRUCTOR,
new MonthYear(1, 2011), false));
/* Add Staff */
status("Adding staff");
for (Staff staff : faculty) {
db.addFaculty(staff);
db.getCommittee(com1).addAtLargeMember(
db.getFaculty(staff.getName()));
}
/* Check name pointerness */
status("Checking that changes are reflected through JSON");
db.getFaculty("John Doe").setName("John Fro");
String json = gson.toJson(db);
BufferedWriter writer = null;
try {
writer = new BufferedWriter(
new FileWriter("fopsdb.json", false));
writer.write(json, 0, json.length());
writer.flush();
//gson.toJson(db, writer);
} catch (IOException e) {
System.err.println("Cannot open file fopsdb.json");
System.exit(1);
}
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
System.err.println("Could not close writer, not aborting.");
}
}
System.out.println("Checking that file read in properly");
BufferedReader reader = null;
FopsDB db2 = null;
try {
reader = new BufferedReader(
new FileReader("fopsdb.json"));
db2 = gson.fromJson(reader, FopsDB.class);
} catch (IOException e) {
System.err.println("Cannot open file fopsdb.json");
System.exit(1);
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
System.err.println("Could not close reader, not aborting.");
}
}
if (db2 != null) {
System.out.println(gson.toJson(db2));
} else {
System.out.println("Ruh roh, Raggy! db2 did not load!");
}
/* Check pointers again */
System.out.println("Checking that pointers still work");
db2.getFaculty("John Fro").setName("John Doe");
json = gson.toJson(db2);
System.out.println(json);
} |
d0dacc62-3a85-40cb-b2af-6fb9c0ff4b53 | 6 | public static void copyFolder(File src, File dest)
{
try
{
if(src.isDirectory())
{
if(!dest.exists())
{
dest.mkdir();
System.out.println("Directory copied from " + src + " to " + dest);
}
String files[] = src.list();
for(String file : files)
{
File srcFile = new File(src, file);
File destFile = new File(dest, file);
copyFolder(srcFile,destFile);
}
} else {
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0)
{
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} |
4695cd51-ae4b-4792-bd2f-1430ed59d3b2 | 7 | private static void loadOptions() {
File inputFile = new File("haven.conf");
if (!inputFile.exists()) {
return;
}
try {
options.load(new FileInputStream("haven.conf"));
} catch (IOException e) {
System.out.println(e);
}
String hideObjects = options.getProperty("hideObjects", "");
String hideHighlight = options.getProperty("hcolor", "255,0,0,128");
// System.out.println(hideHighlight);
String clist[] = hideHighlight.split(",");
if (clist.length != 4) {
clist[0] = "255";
clist[1] = "0";
clist[2] = "0";
clist[0] = "128";
}
// String salpha = hideHighlight.substring(8);
// hideAlpha = Integer.parseInt(salpha, 16);
// hideHighlight = hideHighlight.substring(0, 8);
// hideColor = Color.decode(hideHighlight);
hideColor = new Color(Integer.valueOf(clist[0]), Integer.valueOf(clist[1]),
Integer.valueOf(clist[2]), Integer.valueOf(clist[3]));
GoogleTranslator.apikey = options.getProperty("GoogleAPIKey",
"AIzaSyCuo-ukzI_J5n-inniu2U7729ZfadP16_0");
zoom = options.getProperty("zoom", "false").equals("true");
noborders = options.getProperty("noborders", "false").equals("true");
new_minimap = options.getProperty("new_minimap", "true").equals("true");
new_chat = options.getProperty("new_chat", "true").equals("true");
use_smileys = options.getProperty("use_smileys", "true").equals("true");
isMusicOn = options.getProperty("music_on", "true").equals("true");
isSoundOn = options.getProperty("sound_on", "true").equals("true");
showDirection = options.getProperty("show_direction", "true").equals(
"true");
showNames = options.getProperty("showNames", "true").equals("true");
showOtherNames = options.getProperty("showOtherNames", "false").equals(
"true");
showBeast = options.getProperty("showBeast", "false").equals("true");
showRadius = options.getProperty("showRadius", "false").equals("true");
showHidden = options.getProperty("showHidden", "false").equals("true");
simple_plants = options.getProperty("simple_plants", "false").equals(
"true");
objectHighlighting = options.getProperty("objMouseHLight", "false")
.equals("true"); // Kerri
onlineNotifier = options.getProperty("onlineNotifier", "false").equals(
"true"); // Kerri
showDayTime = options.getProperty("showDayTime", "false")
.equals("true"); // Kerri
objectBlink = options.getProperty("objectBlink", "false")
.equals("true"); // Kerri
autoSaveMinimaps = options.getProperty("autoSaveMinimaps", "false").equals("true"); // Kerri
sshot_compress = options.getProperty("sshot_compress", "false").equals(
"true");
sshot_noui = options.getProperty("sshot_noui", "false").equals("true");
sshot_nonames = options.getProperty("sshot_nonames", "false").equals(
"true");
newclaim = options.getProperty("newclaim", "true").equals("true");
showq = options.getProperty("showq", "true").equals("true");
showpath = options.getProperty("showpath", "false").equals("true");
// Kerri
hideTressp = options.getProperty("hideTressp", "false").equals("true");
hideTheft = options.getProperty("hideTheft", "false").equals("true");
hideAsslt = options.getProperty("hideAsslt", "false").equals("true");
hideBatt = options.getProperty("hideBatt", "false").equals("true");
hideVand = options.getProperty("hideVand", "false").equals("true");
hideMurd = options.getProperty("hideMurd", "false").equals("true");
//
show_minimap_profits = options.getProperty("show_minimap_profits",
"false").equals("true");
toggleCA = options.getProperty("toggleCA", "false").equals("true");
toggleTR = options.getProperty("toggleTR", "false").equals("true");
toggleCL = options.getProperty("toggleCL", "false").equals("true");
show_gob_health = options.getProperty("show_gob_health", "false")
.equals("true");
show_minimap_players = options.getProperty("show_minimap_players",
"false").equals("true");
show_minimap_radius = options.getProperty("show_minimap_radius",
"false").equals("true");
sfxVol = Integer.parseInt(options.getProperty("sfx_vol", "100"));
musicVol = Integer.parseInt(options.getProperty("music_vol", "100"));
hideObjectList.clear();
if (!hideObjects.isEmpty()) {
for (String objectName : hideObjects.split(",")) {
if (!objectName.isEmpty()) {
hideObjectList.add(objectName);
}
}
}
Resource.checkhide();
timestamp = options.getProperty("timestamp", "false").equals("true");
try {
INIFile ifile = new INIFile("haven.ini");
minimap_highlights = ifile.getSectionColors("HIGHLIGHT", "");
} catch (IOException e) {
e.printStackTrace();
}
} |
9b358d6f-ed3c-4f1c-b137-ccb475d4f9e2 | 8 | public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof CategoryLineAnnotation)) {
return false;
}
CategoryLineAnnotation that = (CategoryLineAnnotation) obj;
if (!this.category1.equals(that.getCategory1())) {
return false;
}
if (this.value1 != that.getValue1()) {
return false;
}
if (!this.category2.equals(that.getCategory2())) {
return false;
}
if (this.value2 != that.getValue2()) {
return false;
}
if (!PaintUtilities.equal(this.paint, that.paint)) {
return false;
}
if (!ObjectUtilities.equal(this.stroke, that.stroke)) {
return false;
}
return true;
} |
ce41c231-afda-4335-b74e-56475b7a0f69 | 8 | public static void main(String[] args) throws Exception {
String env = null;
if (args != null && args.length > 0) {
env = args[0];
}
if (! "dev".equals(env))
if (! "prod".equals(env)) {
System.out.println("Usage: $0 (dev|prod)\n");
System.exit(1);
}
// Topology config
Config conf = new Config();
// Load parameters and add them to the Config
Map configMap = YamlLoader.loadYamlFromResource("config_" + env + ".yml");
conf.putAll(configMap);
log.info(JSONValue.toJSONString((conf)));
// Set topology loglevel to DEBUG
conf.put(Config.TOPOLOGY_DEBUG, JsonPath.read(conf, "$.deck36_storm.debug"));
// Create Topology builder
TopologyBuilder builder = new TopologyBuilder();
// if there are not special reasons, start with parallelism hint of 1
// and multiple tasks. By that, you can scale dynamically later on.
int parallelism_hint = JsonPath.read(conf, "$.deck36_storm.default_parallelism_hint");
int num_tasks = JsonPath.read(conf, "$.deck36_storm.default_num_tasks");
// Create Stream from RabbitMQ messages
// bind new queue with name of the topology
// to the main plan9 exchange (from properties config)
// consuming only CBT-related events by using the rounting key 'cbt.#'
String badgeName = HighFiveBadgeTopology.class.getSimpleName();
String rabbitQueueName = badgeName; // use topology class name as name for the queue
String rabbitExchangeName = JsonPath.read(conf, "$.deck36_storm.HighFiveBolt.rabbitmq.exchange");
String rabbitRoutingKey = JsonPath.read(conf, "$.deck36_storm.HighFiveBolt.rabbitmq.routing_key");
// Get JSON deserialization scheme
Scheme rabbitScheme = new SimpleJSONScheme();
// Setup a Declarator to configure exchange/queue/routing key
RabbitMQDeclarator rabbitDeclarator = new RabbitMQDeclarator(rabbitExchangeName, rabbitQueueName, rabbitRoutingKey);
// Create Configuration for the Spout
ConnectionConfig connectionConfig =
new ConnectionConfig(
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.host"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.port"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.user"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.pass"),
(String) JsonPath.read(conf, "$.deck36_storm.rabbitmq.vhost"),
(Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.heartbeat"));
ConsumerConfig spoutConfig = new ConsumerConfigBuilder().connection(connectionConfig)
.queue(rabbitQueueName)
.prefetch((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"))
.requeueOnFail()
.build();
// add global parameters to topology config - the RabbitMQSpout will read them from there
conf.putAll(spoutConfig.asMap());
// For production, set the spout pending value to the same value as the RabbitMQ pre-fetch
// see: https://github.com/ppat/storm-rabbitmq/blob/master/README.md
if ("prod".equals(env)) {
conf.put(Config.TOPOLOGY_MAX_SPOUT_PENDING, (Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.prefetch"));
}
// Add RabbitMQ spout to topology
builder.setSpout("incoming",
new RabbitMQSpout(rabbitScheme, rabbitDeclarator),
parallelism_hint)
.setNumTasks((Integer) JsonPath.read(conf, "$.deck36_storm.rabbitmq.spout_tasks"));
// construct command to invoke the external bolt implementation
ArrayList<String> command = new ArrayList(15);
// Add main execution program (php, hhvm, zend, ..) and parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.executor"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.executor_params"));
// Add main command to be executed (app/console, the phar file, etc.) and global context parameters (environment etc.)
command.add((String) JsonPath.read(conf, "$.deck36_storm.php.main"));
command.addAll((List<String>) JsonPath.read(conf, "$.deck36_storm.php.main_params"));
// Add main route to be invoked and its parameters
command.add((String) JsonPath.read(conf, "$.deck36_storm.HighFiveBolt.main"));
List boltParams = (List<String>) JsonPath.read(conf, "$.deck36_storm.HighFiveBolt.params");
if (boltParams != null)
command.addAll(boltParams);
// Log the final command
log.info("Command to start bolt for HighFive badge: " + Arrays.toString(command.toArray()));
// Add constructed external bolt command to topology using MultilangAdapterBolt
builder.setBolt("badge",
new MultilangAdapterBolt(command, "badge"),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("incoming");
builder.setBolt("rabbitmq_router",
new Plan9RabbitMQRouterBolt(
(String) JsonPath.read(conf, "$.deck36_storm.HighFiveBolt.rabbitmq.target_exchange"),
"HighFive" // RabbitMQ routing key
),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("badge");
builder.setBolt("rabbitmq_producer",
new Plan9RabbitMQPushBolt(),
parallelism_hint)
.setNumTasks(num_tasks)
.shuffleGrouping("rabbitmq_router");
if ("dev".equals(env)) {
LocalCluster cluster = new LocalCluster();
cluster.submitTopology(badgeName + System.currentTimeMillis(), conf, builder.createTopology());
Thread.sleep(2000000);
}
if ("prod".equals(env)) {
StormSubmitter.submitTopology(badgeName + "-" + System.currentTimeMillis(), conf, builder.createTopology());
}
} |
d6a52dc3-447f-4374-8c48-09c9b41d9bef | 3 | public void setKey(String key) {
byte[] keybyte = key.getBytes();
if (keybyte == null) {
throw new RuntimeException("No key");
} else if (keybyte.length < 16) {
throw new RuntimeException("Key too short");
}
// Change bytes for ints
IntBuffer intBuf = ByteBuffer.wrap(keybyte).order(ByteOrder.BIG_ENDIAN)
.asIntBuffer();
int[] array = new int[intBuf.remaining()];
intBuf.get(array);
for (int i = 0; i < 4; i++) {
this.key[i] = array[i];
}
} |
a786e197-badd-4d81-aa5e-872ce6993750 | 7 | public PageInfo parse_stream_page(RandomAccessFile s, long offset) throws IOException {
long[] result = new long[3]; // [header_size, payload_size]
byte[] p_header = new byte[OGG_PAGE_SIZE]; // buffer for the page header
byte[] scratch;
int bread = 0; // number of bytes read
int psize = 0; // payload-size
int nsegs = 0; // Number of segments
s.seek(offset);
bread = s.read(p_header);
if(bread != OGG_PAGE_SIZE)
xdie("Unable to read() OGG_PAGE_HEADER");
if((new String(p_header, 0, 5)).equals("OggS\0") != true)
xdie("Invalid magic - not an ogg file?");
nsegs = b2u(p_header[26]);
// debug("> file seg: "+nsegs);
if(nsegs > 0) {
scratch = new byte[nsegs];
bread = s.read(scratch);
if(bread != nsegs)
xdie("Failed to read segtable");
for(int i=0; i<nsegs; i++) {
psize += b2u(scratch[i]);
}
}
PageInfo pi = new PageInfo();
pi.header_len = (s.getFilePointer() - offset);
pi.payload_len = psize;
pi.type = -1;
/* next byte is most likely the type -> pre-read */
if(psize >= 1 && s.read(p_header, 0, 1) == 1) {
pi.type = b2u(p_header[0]);
}
return pi;
} |
fd7df8dc-cab0-449f-a1d8-175de83e7b54 | 0 | private Command TestSteps2() {
// TODO Auto-generated method stub
getDriver().get("http://www.google.com/webhp?complete=1&hl=en");
return null;
} |
580330af-4dc2-43d5-b4a5-1e3911e2bcfd | 3 | private Boolean checkForCommas (File dataFile) {
m_delimiter="";
try {
m_fileScan = new Scanner(dataFile);
} catch (FileNotFoundException e) {
return false;
}
m_fileScan.useDelimiter(m_delimiter);
while(m_fileScan.hasNext()){
String m_charCheck= m_fileScan.next();
if(m_charCheck.equals(",")){
return true;
}
}
return false;
} |
4cc92f8e-51df-4cc0-9f6a-dc3f964952ce | 5 | protected void processEndSimulation()
{
resList_.clear();
arList_.clear();
if (regionalList_ != null) {
regionalList_.clear();
}
if (globalResList_ != null) {
globalResList_.clear();
}
if (globalResARList_ != null) {
globalResARList_.clear();
}
if (userList_ != null) {
userList_.clear();
}
if (userARList_ != null) {
userARList_.clear();
}
} |
83a42962-7784-48b6-99f7-93e545bfea11 | 5 | public int largestRectangleArea(int[] height) {
if (height.length == 0)
return 0;
int maxArea = height[0];
Stack<Integer> stack = new Stack<Integer>();
int[] h = Arrays.copyOf(height, height.length + 1);
int i = 0;
while (i < h.length) {
if (stack.isEmpty() || h[i] >= h[stack.peek()]) {
stack.push(i++);
} else {
int temp = stack.pop();
maxArea = Math.max(maxArea, h[temp]
* (stack.isEmpty() ? i : i - stack.peek() - 1));
}
}
return maxArea;
} |
e662b87f-1548-4e66-a4ca-64072dc1cf89 | 4 | public double getDiffuseLayerCapPerSquareMetre(){
if(this.psi0set && this.sigmaSet){
return this.diffCap;
}
else{
if(this.sigmaSet){
this.getSurfacePotential();
return this.diffCap;
}
else{
if(this.psi0set){
this.getSurfaceChargeDensity();
return this.diffCap;
}
else{
System.out.println("Class: GouyChapmanStern\nMethod: getDiffuseLayerCapPerSquareMetre\nThe value of the diffuse layer capacitance has not been calculated\ninfinity returned");
System.out.println("Neither a surface potential nor a surface charge density have been entered");
return Double.POSITIVE_INFINITY;
}
}
}
} |
b8eca465-8fa8-4493-8650-9a7430ed93d2 | 1 | @Override
public void setVisible(boolean visibility) {
super.setVisible(visibility);
button.setVisible(visibility);
lineNumber.setVisible(visibility);
if (pShowIndicators) {
iComment.setVisible(visibility);
iEditable.setVisible(visibility);
iMoveable.setVisible(visibility);
} else {
iComment.setVisible(false);
iEditable.setVisible(false);
iMoveable.setVisible(false);
}
} |
8bf2cc4c-ca5f-4ba2-9bd1-51842c565c4c | 1 | public boolean doTransformations() {
StructuredBlock last = flowBlock.lastModified;
return CreateCheckNull.transformJikes(this, last)
|| CreateClassField.transform(this, last);
} |
1021c8ec-ef35-4c6f-98f5-408cb9a056a2 | 5 | private static void parseFrameworkConfig(Element framework) {
List<?> children = framework.getChildren();
Iterator<?> iterator = children.iterator();
while(iterator.hasNext()){
Element child = (Element)iterator.next();
String fieldName = child.getName();
// test whether this child has attributes
if(child.getAttributes().size() <= 0) { // this tag has no attributes
continue;
}
String value = child.getAttributeValue("value");
if(value == null) { // did not find
Main.fatalError("Error while parsing the configuration file: The entry '" + fieldName +
"' contains attributes, but none is called 'value'.");
}
Configuration.setFrameworkConfigurationEntry(fieldName, value);
}
} |
11211b46-ff3d-4370-8129-bfd6cdc7174d | 8 | int skipTo(int target) throws IOException {
if (!haveSkipped) {
// first time, load skip levels
loadSkipLevels();
haveSkipped = true;
}
// walk up the levels until highest level is found that has a skip
// for this target
int level = 0;
while (level < numberOfSkipLevels - 1 && target > skipDoc[level + 1]) {
level++;
}
while (level >= 0) {
if (target > skipDoc[level]) {
if (!loadNextSkip(level)) {
continue;
}
} else {
// no more skips on this level, go down one level
if (level > 0 && lastChildPointer > skipStream[level - 1].getFilePointer()) {
seekChild(level - 1);
}
level--;
}
}
return numSkipped[0] - skipInterval[0] - 1;
} |
03e95ad8-6dda-43c2-98d1-f15679b3ba80 | 1 | private Set<String> extractFillColors(Document document) throws XPathExpressionException {
Set<String> colors = new HashSet<String>();
Element root = document.getDocumentElement();
XPathExpression xPathExpression = xml.compileXPath("descendant::*[@fill]/@fill");
NodeList nodeList = (NodeList)xPathExpression.evaluate(root, XPathConstants.NODESET);
for(int i=0;i<nodeList.getLength();i++) {
Node node = nodeList.item(i);
colors.add(node.getNodeValue());
}
return colors;
} |
67ffa029-060b-45d7-b72b-ed62b6dcff1a | 0 | public Grille setBooleans(boolean[][] grid) {
this.grid = grid;
return this;
} |
58c88093-ccd8-47c4-9646-337476d6da6d | 1 | protected void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
if(JOptionPane.showConfirmDialog(rootPane, "Você tem certeza que deseja cancelar?")== 0){
this.dispose();
}
}//GEN-LAST:event_btnCancelarActionPerformed |
75e87b64-ded2-4ec8-b936-4a451bc91408 | 8 | public static Skolem insertElementComputation(Skolem list, IntegerWrapper narg, Stella_Object element) {
if (!(Logic.enumeratedListP(list))) {
return (null);
}
{ int n = narg.wrapperValue;
Vector elements = list.definingProposition.arguments;
int nelements = elements.length() - 1;
List newelements = List.newList();
if (n < 0) {
n = nelements + n + 1;
}
if ((n < 0) ||
(n > nelements)) {
return (null);
}
{ Stella_Object elt = null;
Vector vector000 = elements;
int index000 = 0;
int length000 = vector000.length();
int i = Stella.NULL_INTEGER;
int iter000 = 0;
int upperBound000 = nelements - 1;
for (;(index000 < length000) &&
(iter000 <= upperBound000); index000 = index000 + 1, iter000 = iter000 + 1) {
elt = (vector000.theArray)[index000];
i = iter000;
if (i == n) {
newelements.push(element);
}
newelements.push(elt);
}
}
if (n == nelements) {
newelements.push(element);
}
return (Logic.createLogicalList(newelements.reverse()));
}
} |
9129902d-4bb3-40bd-a3f5-b4b85aac2841 | 8 | public Object nextValue() throws JSONException {
char c = nextClean();
String s;
switch (c) {
case '"':
case '\'':
return nextString(c);
case '{':
back();
return new JSONObject(this);
case '[':
case '(':
back();
return new JSONArray(this);
}
/*
* Handle unquoted text. This could be the values true, false, or
* null, or it can be a number. An implementation (such as this one)
* is allowed to also accept non-standard forms.
*
* Accumulate characters until we reach the end of the text or a
* formatting character.
*/
StringBuffer sb = new StringBuffer();
while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) {
sb.append(c);
c = next();
}
back();
s = sb.toString().trim();
if (s.equals("")) {
throw syntaxError("Missing value");
}
return JSONObject.stringToValue(s);
} |
4c33bb5f-c7e7-4051-bada-826dce996a35 | 3 | public void run()
{
while(running)
{
while(Log.hasNewEntry())
{
textArea.append(Log.getNextEntry() + "\n");
}
try {
sleep(10);
} catch (InterruptedException e) {
yield();
}
}
} |
b15dba03-d32f-4493-aa7c-86baf668c6e2 | 7 | public void onDraw(Graphics g, int viewX, int viewY)
{
if ((status&World.ST_INVISIBLE)!=0)
{
return;
}
int offs = x % 8;
if (!done)
{
//x+=move;
g.drawArc(((x-2)-viewX)*3, ((y-10)-viewY)*3, 4, 4, 0, 360);
g.drawLine(((x)-viewX)*3, ((y-6)-viewY)*3, ((x)-viewX)*3, ((y-3)-viewY)*3);
g.drawLine(((x-2)-viewX)*3, ((y-4)-viewY)*3, ((x+2)-viewX)*3, ((y-4)-viewY)*3);
g.drawLine(((x)-viewX)*3, ((y-3)-viewY)*3, ((x+offs-2)-viewX)*3, ((y)-viewY)*3);
g.drawLine(((x)-viewX)*3, ((y-3)-viewY)*3, ((x+2-offs)-viewX)*3, ((y)-viewY)*3);
}
else
{
int yUp = 20;
if (Integer.signum(move)==-1)
{
left = -1;
}
if (Integer.signum(move)==1)
{
left = 1;
}
Graphics2D g2 = (Graphics2D)g;
g2.scale(left,1);
g2.drawImage(bodyParts[0], (x-viewX)*3*left+(left<0?-18:0), (y-yUp-6-viewY)*3, null);
g2.drawImage(bodyParts[1], (int)(x+2-((bodyParts[1].getWidth(null)-23)/5)-viewX)*3*left+(left<0?-(6+(bodyParts[1].getWidth(null)-23)):0), ((y-yUp-16-((bodyParts[1].getHeight(null)-31))/3)-viewY)*3, null);
double ffs = Math.toRadians(((4-offs)*6));
AffineTransform previousAT = g2.getTransform();
g2.translate((x-3-viewX)*3*left, ((y-yUp-6)-viewY)*3);
g2.rotate(Math.toRadians(leftArmAngle-90),4*(left+1),2);
g2.drawImage(bodyParts[2],0 , 0, null);
g2.setTransform(previousAT);
g2.translate((((x-3-viewX)+lengthdir_x(6*left, leftArmAngle*left)))*left*3, (((y-yUp-6)-this.lengthdir_y(6*left,leftArmAngle*left))-viewY)*3);
g2.rotate(Math.toRadians(leftArmAngle-90),4*(left+1),2);
g2.drawImage(bodyParts[3], 0,0, null);
g2.setTransform(previousAT);
g2.translate((x+9-viewX)*3*left, ((y-yUp-6)-viewY)*3);
g2.rotate(Math.toRadians(rightArmAngle-90),8-left*4,4);
g2.drawImage(bodyParts[2], 0, 0, null);
g2.setTransform(previousAT);
g2.translate((((x+9-viewX)+this.lengthdir_x(6*left, rightArmAngle*left))*3)*left, (((y-yUp-6)-this.lengthdir_y(6*left,rightArmAngle*left))-viewY)*3);
g2.rotate(Math.toRadians(rightArmAngle-90),8-left*4,4);
g2.drawImage(bodyParts[3], 0, 0, null);
g2.setTransform(previousAT);
g2.drawImage(bodyParts[4], (x+1-viewX)*3*left, ((y-yUp+7)-viewY)*3, null);
g2.drawImage(bodyParts[4], (x+5-viewX)*3*left, ((y-yUp+7)-viewY)*3, null);
g2.translate((x+5-viewX)*3*left, ((y+13)-viewY-yUp)*3);
g2.rotate(ffs);
g2.drawImage(bodyParts[5], 0, 0, null);
g2.setTransform(previousAT);
g2.translate((x+1-viewX)*3*left, ((y+13)-viewY-yUp)*3);
g2.rotate(-ffs);
g2.drawImage(bodyParts[5], 0, 0, null);
g2.setTransform(previousAT);
g2.scale(left, 1);
}
g.setColor(myTeam?Color.GREEN:Color.MAGENTA);
g.drawString(username, ((x-(username.length()))-viewX)*3, (y-40-viewY)*3);
} |
a64dac5a-f5d0-4dbb-9ced-07a28e27aa94 | 7 | public static void send(Socket socket, Vector<String> vector){
System.out.println("Sending " + vector.size() + " files");
try {
PrintWriter server = new PrintWriter(socket.getOutputStream());
// Tell them how many files
server.println(vector.size());
for(String fileName : vector){
server.println(fileName);
server.flush();
String response = readLine(socket);
File file = new File(fileName);
if(response.equals(EXISTS)){
server.println(getMD5Digest(file));
server.flush();
response = readLine(socket);
if(response.equals(CACHED) || response.equals(DECLINE))
continue; // They don't want or need this file, go to the next
}else if(response.equals(ACCEPT)){
// send the file as normal
}
long fileSize = file.length();
long bytesRead = 0;
int read = 0;
byte[] buffer = new byte[4096];
server.println(fileSize);
server.println(buffer.length);
server.flush();
System.out.println("Transfering " + fileName);
BufferedInputStream reader = new BufferedInputStream(new FileInputStream(file));
while(bytesRead < fileSize){
read = reader.read(buffer);
socket.getOutputStream().write(buffer,0,read);
bytesRead += read;
}
socket.getOutputStream().flush();
System.out.println("Done Transfering " + fileName);
}
} catch (IOException e) {
e.printStackTrace();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.