auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public void createObservation_shouldCreateObservationWithCodedConcept() throws Exception { DWRObsService dwrService = new DWRObsService(); ConceptService conceptService = Context.getConceptService(); Person person = Context.getPersonService().getPerson(2); dwrService.createObs(2, null, 21, "7", "12/12/2014"); List<Obs> obsList = Context.getObsService().getObservationsByPerson(person); Concept concept = conceptService.getConcept(21); Concept answerConcept = conceptService.getConcept(7); Obs addedObs = null; for (Obs obs : obsList) { if (concept.getId().equals(obs.getConcept().getId())) { addedObs = obs; } } assertNotNull(addedObs); assertNotNull(addedObs.getValueCoded()); assertEquals(answerConcept.getId(), addedObs.getValueCoded().getId()); }

Target:
public void createObservation_shouldCreateObservationWithCodedConcept() throws Exception { DWRObsService dwrService = new DWRObsService(); ConceptService conceptService = Context.getConceptService(); ObsService obsService = Context.getObsService(); Person person = Context.getPersonService().getPerson(2); Concept concept = conceptService.getConcept(21); List<Obs> obsListBefore = obsService.getObservationsByPersonAndConcept(person, concept); dwrService.createObs(2, null, 21, "7", "1/12/2014"); List<Obs> obsListAfter = obsService.getObservationsByPersonAndConcept(person, concept); assertEquals(obsListBefore.size() + 1, obsListAfter.size()); Concept answerConcept = conceptService.getConcept(7); Obs addedObs = null; addedObs = (Obs) CollectionUtils.subtract(obsListAfter, obsListBefore).iterator().next(); assertNotNull(addedObs); assertNotNull(addedObs.getValueCoded()); assertEquals(answerConcept.getId(), addedObs.getValueCoded().getId()); }
Source:
public static ThreadPoolExecutor newFixedThreadPool(int numThreads, String name) { return newFixedThreadPool(numThreads, new NamedThreadFactory(name)); }

Target:
public static ThreadPoolExecutor newFixedThreadPool(int numThreads, String name) { return newFixedThreadPool(numThreads, new NamedThreadFactory(name, true)); }
Source:
private String generateTextSrc(SlideshowModel slideshow, int position) { final String prefix = "text_"; final String postfix = ".txt"; StringBuilder src = new StringBuilder(prefix).append(position).append(postfix); boolean hasDupSrc = false; do { for (SlideModel model : slideshow) { if (model.hasText()) { if (model.getText().getSrc().equals(src.toString())) { src = new StringBuilder(prefix).append(position + 1).append(postfix); hasDupSrc |= true; break; } } hasDupSrc &= false; } } while (hasDupSrc); return src.toString(); }

Target:
private String generateTextSrc(SlideshowModel slideshow, int position) { final String prefix = "text_"; final String postfix = ".txt"; StringBuilder src = new StringBuilder(prefix).append(position).append(postfix); boolean hasDupSrc = false; do { for (SlideModel model : slideshow) { if (model.hasText()) { String testSrc = model.getText().getSrc(); if (testSrc != null && testSrc.equals(src.toString())) { src = new StringBuilder(prefix).append(position + 1).append(postfix); hasDupSrc |= true; break; } } hasDupSrc = false; } } while (hasDupSrc); return src.toString(); }
Source:
public HaxeGenericSpecialization getSpecialization() { if (LOG.isTraceEnabled()) LOG.trace(traceMsg(null)); HaxeGenericSpecialization specialization = getUserData(SPECIALIZATION_KEY); if (specialization == null) { specialization = getSpecializationInternal(); putUserData(SPECIALIZATION_KEY, specialization); } return specialization; }

Target:
public HaxeGenericSpecialization getSpecialization() { HaxeExpression expression = this; if (this instanceof HaxeCallExpression) { expression = ((HaxeCallExpression)this).getExpression(); } else if (this instanceof HaxeNewExpression) { HaxeNewExpression newExpression = (HaxeNewExpression)this; HaxeClass haxeClass = (HaxeClass)newExpression.getType().getReferenceExpression().resolve(); final HaxeClassResolveResult result = HaxeClassResolveResult.create(haxeClass); result.specializeByParameters(newExpression.getType().getTypeParam()); return result.getSpecialization(); } final HaxeClassResolveResult result = tryGetLeftResolveResult(expression); return result != HaxeClassResolveResult.EMPTY ? result.getSpecialization() : null; }
Source:
public boolean isIgnoredInOldIndex(IndexDiffCacheEntry entry, String path) { if (entry == null) return false; IndexDiffData indexDiff = entry.getIndexDiff(); if (indexDiff == null) return false; for (String s : indexDiff.getIgnoredNotInIndex()) { String sWithSlash = s; if (!s.endsWith("/")) { sWithSlash = s + '/'; } if (path.equals(s) || path.startsWith(sWithSlash)) { return true; } } return false; }

Target:
public boolean isIgnoredInOldIndex(IndexDiffCacheEntry entry, String path) { if (entry == null || gitIgnoreChanged) return false; IndexDiffData indexDiff = entry.getIndexDiff(); if (indexDiff == null) return false; for (String s : indexDiff.getIgnoredNotInIndex()) { String sWithSlash = s; if (!s.endsWith("/")) { sWithSlash = s + '/'; } if (path.equals(s) || path.startsWith(sWithSlash)) { return true; } } return false; }
Source:
@Override InputStream getInputStream() throws IOException { return Utils.getContactPhotoStream(context.getContentResolver(), uri); }

Target:
private InputStream getInputStream() throws IOException { ContentResolver contentResolver = context.getContentResolver(); Uri uri = this.uri; if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) { if (uri.toString().startsWith(ContactsContract.Contacts.CONTENT_LOOKUP_URI.toString())) { uri = ContactsContract.Contacts.lookupContact(contentResolver, uri); if (uri == null) { return null; } } return openContactPhotoInputStream(contentResolver, uri); } else { return ContactPhotoStreamIcs.get(contentResolver, uri); } }
Source:
private String getAndroidCommand(){ String command = "android"; return isWindows() ? "cmd /c " + command : command; }

Target:
private String getAndroidCommand(){ String command = "android"; return isWindows() ? "cmd /c " + command : "./" + command; }
Source:
private void querySubprocess() { try { markWaitingSubprocess(); _logHandler.setUpContext(_process, _context); _process.writeSpoutMsg(_spoutMsg); while (true) { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in spout message: " + shellMsg); } setHeartbeat(); if (command.equals("sync")) { return; } else if (command.equals("log")) { _logHandler.log(shellMsg); } else if (command.equals("error")) { handleError(shellMsg.getMsg()); } else if (command.equals("emit")) { String stream = shellMsg.getStream(); Long task = shellMsg.getTask(); List<Object> tuple = shellMsg.getTuple(); Object messageId = shellMsg.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); if (shellMsg.areTaskIdsNeeded()) { _process.writeTaskIds(outtasks); } } else { _collector.emitDirect((int) task.longValue(), stream, tuple, messageId); } } else if (command.equals("metrics")) { handleMetrics(shellMsg); } else { throw new RuntimeException("Unknown command received: " + command); } } } catch (Exception e) { String processInfo = _process.getProcessInfoString() + _process.getProcessTerminationInfoString(); throw new RuntimeException(processInfo, e); } finally { completedWaitingSubprocess(); } }

Target:
private void querySubprocess() { try { markWaitingSubprocess(); _process.writeSpoutMsg(_spoutMsg); while (true) { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in spout message: " + shellMsg); } setHeartbeat(); if (command.equals("sync")) { return; } else if (command.equals("log")) { _logHandler.log(shellMsg); } else if (command.equals("error")) { handleError(shellMsg.getMsg()); } else if (command.equals("emit")) { String stream = shellMsg.getStream(); Long task = shellMsg.getTask(); List<Object> tuple = shellMsg.getTuple(); Object messageId = shellMsg.getId(); if (task == 0) { List<Integer> outtasks = _collector.emit(stream, tuple, messageId); if (shellMsg.areTaskIdsNeeded()) { _process.writeTaskIds(outtasks); } } else { _collector.emitDirect((int) task.longValue(), stream, tuple, messageId); } } else if (command.equals("metrics")) { handleMetrics(shellMsg); } else { throw new RuntimeException("Unknown command received: " + command); } } } catch (Exception e) { String processInfo = _process.getProcessInfoString() + _process.getProcessTerminationInfoString(); throw new RuntimeException(processInfo, e); } finally { completedWaitingSubprocess(); } }
Source:
void logRequestHeaders() { Header[] headers=postMethod.getRequestHeaders(); Map<String, String> headerMap = new HashMap<String, String>(); for(Header header:headers){ headerMap.put(header.getName(), header.getValue()); } logger.log(Logger.LT_INFO, "Request Headers: " + headerMap); }

Target:
public void logRequestHeaders() { List<Header> reqheaders=Arrays.asList(postMethod.getRequestHeaders()); logger.log(Logger.LT_INFO, "Request Headers: " +reqheaders); }
Source:
protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { boolean ADMIN_MODE = PageRequestModeUtil.isAdminMode( req.getSession() ); boolean notRedirect = notRedirect( req ); if ( ADMIN_MODE && !notRedirect ){ String pageUrl = req.getAttribute("javax.servlet.forward.request_uri").toString(); if (pageUrl != null && pageUrl.indexOf(IN_FRAME_PARAMETER_NAME) == -1) { String redirectURL = getRedirectURL(pageUrl); response.sendRedirect(redirectURL); return; } } super.service(req, response); }

Target:
protected void service(HttpServletRequest req, HttpServletResponse response) throws ServletException, IOException { boolean adminMode = PageRequestModeUtil.isAdminMode( req.getSession() ); boolean notRedirect = notRedirect( req ); if ( adminMode && !notRedirect ){ String pageUrl = req.getAttribute(Constants.ORIGINAL_REQUEST_URL_HTTP_HEADER).toString(); if (pageUrl != null && pageUrl.indexOf(IN_FRAME_PARAMETER_NAME) == -1) { String redirectURL = PORTLET_URL_UTIL.getPortletUrl(PortletID.SITE_BROWSER, CollectionsUtils.map("url", pageUrl)); response.sendRedirect(redirectURL); return; } } super.service(req, response); }
Source:
public TrendsResult getTrends(@Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("time_scale") String timeScaleString) { final TimeScale timeScale = TimeScale.fromString(timeScaleString); final TrendsResult result = trendsProcessor.getAllTrends(accessToken.accountId, timeScale); if (result.graphs.isEmpty()) { throw new WebApplicationException(Response.Status.NOT_FOUND); } return result; }

Target:
public TrendsResult getTrends(@Scope(OAuthScope.INSIGHTS_READ) final AccessToken accessToken, @PathParam("time_scale") String timeScaleString) { try { final TimeScale timeScale = TimeScale.fromString(timeScaleString); return trendsProcessor.getAllTrends(accessToken.accountId, timeScale); } catch (IllegalArgumentException iae) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST) .entity(new JsonError(Response.Status.BAD_REQUEST.getStatusCode(), iae.getMessage())).build()); } }
Source:
static void computeUpdateLineAmts(@NonNull final I_I_BankStatement importRecord) { final String amtFormat = getAmtFormat(importRecord); if (X_I_BankStatement.AMTFORMAT_AmountPlusIndicator.equals(amtFormat)) { final BigDecimal trxAmt; final boolean isDebit = "S".equals(importRecord.getDebitOrCreditIndicator()); if (isDebit) { trxAmt = importRecord.getDebitOrCreditAmt().negate(); } else { trxAmt = importRecord.getDebitOrCreditAmt(); } importRecord.setTrxAmt(trxAmt); final BigDecimal stmtAmt = trxAmt.add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); } else if (X_I_BankStatement.AMTFORMAT_DebitPlusCredit.equals(amtFormat)) { final BigDecimal stmtAmt = importRecord.getCreditStmtAmt().subtract(importRecord.getDebitStmtAmt()); importRecord.setStmtAmt(stmtAmt); final BigDecimal trxAmt = stmtAmt.subtract(importRecord.getInterestAmt()).subtract(importRecord.getChargeAmt()); importRecord.setTrxAmt(trxAmt); } else if (X_I_BankStatement.AMTFORMAT_Straight.equals(amtFormat)) { importRecord.setStmtAmt(importRecord.getTrxAmt()); } { final BigDecimal sum = importRecord.getTrxAmt().add(importRecord.getInterestAmt()).add(importRecord.getChargeAmt()); if (importRecord.getStmtAmt().compareTo(sum) != 0) { throw new AdempiereException("Invalid amount"); } } }

Target:
static void computeUpdateLineAmts(@NonNull final I_I_BankStatement importRecord) { final String amtFormat = getAmtFormat(importRecord); switch (amtFormat) { case X_I_BankStatement.AMTFORMAT_AmountPlusIndicator: { final BigDecimal trxAmt; final boolean isDebit = X_I_BankStatement.DEBITORCREDITINDICATOR_Debit.equals(importRecord.getDebitOrCreditIndicator()); if (isDebit) { trxAmt = importRecord.getDebitOrCreditAmt().negate(); } else { trxAmt = importRecord.getDebitOrCreditAmt(); } importRecord.setTrxAmt(trxAmt); final BigDecimal stmtAmt = trxAmt.add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); break; } case X_I_BankStatement.AMTFORMAT_DebitPlusCredit: { final BigDecimal stmtAmt = importRecord.getCreditStmtAmt().subtract(importRecord.getDebitStmtAmt()); importRecord.setStmtAmt(stmtAmt); final BigDecimal trxAmt = stmtAmt.subtract(importRecord.getChargeAmt()).subtract(importRecord.getInterestAmt()); importRecord.setTrxAmt(trxAmt); break; } case X_I_BankStatement.AMTFORMAT_Straight: { final BigDecimal stmtAmt = importRecord.getTrxAmt().add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); importRecord.setStmtAmt(stmtAmt); break; } } { final BigDecimal sum = importRecord.getTrxAmt().add(importRecord.getChargeAmt()).add(importRecord.getInterestAmt()); if (importRecord.getStmtAmt().compareTo(sum) != 0) { throw new AdempiereException("Invalid amount"); } } }
Source:
public List<Flight> search(SearchParams searchParams) { switch (searchParams.getSearchType()) { case Date: return searchByDate(searchParams); break; case Time: return searchByTime(searchParams); break; case Price: return searchByPrice(searchParams); break; } }

Target:
public List<Flight> search(SearchParams searchParams) { try { switch (searchParams.getSearchType()) { case Date: return searchByDate(searchParams); case Time: return searchByTime(searchParams); case Price: return searchByPrice(searchParams); case Destination: return searchByDestination(searchParams); default: return dao.getAllFlights(); } } catch (Exception e) { System.out.println("Something went wrong while searching the flights"); System.out.println(e.getMessage()); return null; } }
Source:
public synchronized void register(SystemStreamPartition systemStreamPartition, String offset) { super.register(systemStreamPartition, offset); if (isStarted) { LOG.warn("Trying to add partition when the connection has already started."); return; } if (StringUtil.isNullOrWhiteSpace(offset)) { switch (config.getStartPosition(systemStreamPartition.getStream())) { case EARLIEST: offset = START_OF_STREAM; break; case LATEST: offset = END_OF_STREAM; break; default: throw new SamzaException( "Unknown starting position config " + config.getStartPosition(systemStreamPartition.getStream())); } } streamPartitionStartingOffsets.put(systemStreamPartition, offset); }

Target:
public void register(SystemStreamPartition systemStreamPartition, String offset) { super.register(systemStreamPartition, offset); if (isStarted) { throw new SamzaException("Trying to add partition when the connection has already started."); } if (streamPartitionOffsets.containsKey(systemStreamPartition)) { String prevOffset = streamPartitionOffsets.get(systemStreamPartition); if (EventHubSystemAdmin.compareOffsets(offset, prevOffset) > -1) { return; } } streamPartitionOffsets.put(systemStreamPartition, offset); }
Source:
public void show(final boolean shwn) throws IOException { if (this.file.exists()) { Files.getFileAttributeView( this.file.toPath(), UserDefinedFileAttributeView.class ).write( MkAttributes.VISIBILITY, Charsets.UTF_8.encode(String.valueOf(shwn)) ); } }

Target:
public void show(final boolean shwn) throws IOException { Files.getFileAttributeView( this.file.toPath(), UserDefinedFileAttributeView.class ).write( MkAttributes.VISIBILITY, StandardCharsets.UTF_8.encode(String.valueOf(shwn)) ); }
Source:
protected SR createFileSR(final Connection conn, final String path) { SR sr = null; PBD pbd = null; try { final String srname = path.trim(); synchronized (srname.intern()) { final Set<SR> srs = SR.getByNameLabel(conn, srname); if (srs != null && !srs.isEmpty()) { return srs.iterator().next(); } final Map<String, String> smConfig = new HashMap<String, String>(); final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); final String uuid = UUID.randomUUID().toString(); sr = SR.introduce(conn, uuid, srname, srname, "file", "file", false, smConfig); final PBD.Record record = new PBD.Record(); record.host = host; record.SR = sr; smConfig.put("location", path); record.deviceConfig = smConfig; pbd = PBD.create(conn, record); pbd.plug(conn); sr.scan(conn); } return sr; } catch (final Exception ex) { try { if (pbd != null) { pbd.destroy(conn); } } catch (final Exception e1) { s_logger.debug("Failed to destroy PBD", ex); } try { if (sr != null) { sr.forget(conn); } } catch (final Exception e2) { s_logger.error("Failed to forget SR", ex); } final String msg = "createFileSR failed! due to the following: " + ex.toString(); s_logger.warn(msg, ex); throw new CloudRuntimeException(msg, ex); } }

Target:
protected SR createFileSR(final Connection conn, final String path) { SR sr = null; PBD pbd = null; try { final String srname = hypervisorResource.getHost().getUuid() + path.trim(); synchronized (srname.intern()) { final Set<SR> srs = SR.getByNameLabel(conn, srname); if (srs != null && !srs.isEmpty()) { return srs.iterator().next(); } final Map<String, String> smConfig = new HashMap<String, String>(); final Host host = Host.getByUuid(conn, hypervisorResource.getHost().getUuid()); final String uuid = UUID.randomUUID().toString(); sr = SR.introduce(conn, uuid, srname, srname, "file", "file", false, smConfig); final PBD.Record record = new PBD.Record(); record.host = host; record.SR = sr; smConfig.put("location", path); record.deviceConfig = smConfig; pbd = PBD.create(conn, record); pbd.plug(conn); sr.scan(conn); } return sr; } catch (final Exception ex) { try { if (pbd != null) { pbd.destroy(conn); } } catch (final Exception e1) { s_logger.debug("Failed to destroy PBD", ex); } try { if (sr != null) { sr.forget(conn); } } catch (final Exception e2) { s_logger.error("Failed to forget SR", ex); } final String msg = "createFileSR failed! due to the following: " + ex.toString(); s_logger.warn(msg, ex); throw new CloudRuntimeException(msg, ex); } }
Source:
public Answer execute(final DeleteStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) { final Connection conn = citrixResourceBase.getConnection(); final StorageFilerTO poolTO = command.getPool(); try { final SR sr; if (command.getRemoveDatastore()) { Map<String, String> details = command.getDetails(); String srNameLabel = details.get(DeleteStoragePoolCommand.DATASTORE_NAME); sr = citrixResourceBase.getStorageRepository(conn, srNameLabel); } else { sr = citrixResourceBase.getStorageRepository(conn, poolTO.getUuid()); } citrixResourceBase.removeSR(conn, sr); final Answer answer = new Answer(command, true, "success"); return answer; } catch (final Exception e) { final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + poolTO.getHost() + poolTO.getPath(); s_logger.warn(msg, e); return new Answer(command, false, msg); } }

Target:
public Answer execute(final DeleteStoragePoolCommand command, final CitrixResourceBase citrixResourceBase) { final Connection conn = citrixResourceBase.getConnection(); final StorageFilerTO poolTO = command.getPool(); try { final SR sr; if (command.getRemoveDatastore()) { Map<String, String> details = command.getDetails(); String srNameLabel = details.get(DeleteStoragePoolCommand.DATASTORE_NAME); sr = citrixResourceBase.getStorageRepository(conn, srNameLabel); } else { sr = citrixResourceBase.getStorageRepository(conn, poolTO.getUuid()); } citrixResourceBase.removeSR(conn, sr); final Answer answer = new Answer(command, true, "success"); return answer; } catch (final Exception e) { final String msg = "DeleteStoragePoolCommand XenAPIException:" + e.getMessage() + " host:" + citrixResourceBase.getHost().getUuid() + " pool: " + poolTO.getHost() + poolTO.getPath(); s_logger.error(msg, e); return new Answer(command, false, msg); } }
Source:
public TupleDescriptor buildDescriptor (ExecRow row, TupleDescriptor parentTupleDescriptor, DataDictionary dd ) throws StandardException { DataValueDescriptor col; RoleGrantDescriptor descriptor; String oid_string; String roleid; String grantee; String grantor; String wao; boolean isdef; boolean isDefaultRole; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); if (SanityManager.DEBUG) { SanityManager.ASSERT(row.nColumns() == SYSROLES_COLUMN_COUNT, "Wrong number of columns for a SYSROLES row"); } col = row.getColumn(1); oid_string = col.getString(); col = row.getColumn(2); roleid = col.getString(); col = row.getColumn(3); grantee = col.getString(); col = row.getColumn(4); grantor = col.getString(); col = row.getColumn(5); wao = col.getString(); col = row.getColumn(6); isdef = col.getString().equals("Y"); col = row.getColumn(7); if (col == null || col.isNull()) { if (!isdef) isDefaultRole = true; else isDefaultRole = false; } else isDefaultRole = col.getString().equals("Y"); descriptor = ddg.newRoleGrantDescriptor (getUUIDFactory().recreateUUID(oid_string), roleid, grantee, grantor, wao.equals("Y") ? true: false, isdef, isDefaultRole); return descriptor; }

Target:
public TupleDescriptor buildDescriptor (ExecRow row, TupleDescriptor parentTupleDescriptor, DataDictionary dd ) throws StandardException { DataValueDescriptor col; RoleGrantDescriptor descriptor; String oid_string; String roleid; String grantee; String grantor; String wao; boolean isdef; boolean isDefaultRole; DataDescriptorGenerator ddg = dd.getDataDescriptorGenerator(); if (SanityManager.DEBUG) { SanityManager.ASSERT(row.nColumns() == SYSROLES_COLUMN_COUNT, "Wrong number of columns for a SYSROLES row"); } col = row.getColumn(1); oid_string = col.getString(); col = row.getColumn(2); roleid = col.getString(); col = row.getColumn(3); grantee = col.getString(); col = row.getColumn(4); grantor = col.getString(); col = row.getColumn(5); wao = col.getString(); col = row.getColumn(6); isdef = col.getString().equals("Y"); col = row.getColumn(7); if (col == null || col.isNull()) { isDefaultRole = !isdef; } else isDefaultRole = col.getString().equals("Y"); descriptor = ddg.newRoleGrantDescriptor (getUUIDFactory().recreateUUID(oid_string), roleid, grantee, grantor, wao.equals("Y") ? true: false, isdef, isDefaultRole); return descriptor; }
Source:
public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; final long timeout = TimeUnit.SECONDS.toMillis(10L); final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; final Thread server = new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel(new BkBasic(take)), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ); server.start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(timeout, TimeUnit.MILLISECONDS); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }

Target:
public void requestsAreParallel() throws Exception { final int port = new Ports().allocate(); final String uri = String.format("http://localhost:%d", port); final int count = 3; final CountDownLatch started = new CountDownLatch(count); final CountDownLatch completed = new CountDownLatch(count); final Take take = new Take() { @Override public Response act(final Request req) throws IOException { started.countDown(); try { started.await(); } catch (final InterruptedException ex) { throw new IllegalStateException(ex); } completed.countDown(); return new TkEmpty().act(req); } }; new Thread( new Runnable() { @Override public void run() { try { new FtBasic( new BkParallel(new BkBasic(take)), port ).start( new Exit() { @Override public boolean ready() { return completed.getCount() == 0; } } ); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); for (int idx = 0; idx < count; ++idx) { new Thread( new Runnable() { @Override public void run() { try { new JdkRequest(uri) .fetch() .as(RestResponse.class) .assertStatus(HttpURLConnection.HTTP_OK); } catch (final IOException ex) { throw new IllegalStateException(ex); } } } ).start(); } completed.await(1L, TimeUnit.MINUTES); MatcherAssert.assertThat(started.getCount(), Matchers.equalTo(0L)); MatcherAssert.assertThat(completed.getCount(), Matchers.equalTo(0L)); new Ports().release(port); }
Source:
ConnectionHandler createConnectionHandler(String connectionId, String hostname, TransportType transportType) { switch (transportType) { case AMQP: return new ConnectionHandler(connectionId, hostname); case AMQP_WEB_SOCKETS: return new WebSocketsConnectionHandler(connectionId, hostname); default: throw new IllegalArgumentException(String.format(Locale.US, "This transport type '%s' is not supported.", transportType)); } }

Target:
ConnectionHandler createConnectionHandler(String connectionId, String hostname, TransportType transportType) { switch (transportType) { case AMQP: return new ConnectionHandler(connectionId, hostname); case AMQP_WEB_SOCKETS: return new WebSocketsConnectionHandler(connectionId, hostname); default: logger.logAndThrow(new IllegalArgumentException(String.format(Locale.US, "This transport type '%s' is not supported.", transportType))); return null; } }
Source:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", this::index); get(Routes.ElasticProfileAPI.ID, this::show); get(Routes.ElasticProfileAPI.ID + "/usages", this::usages); post("", this::create); put(Routes.ElasticProfileAPI.ID, this::update); delete(Routes.ElasticProfileAPI.ID, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }

Target:
public void setupRoutes() { path(controllerBasePath(), () -> { before("", this::setContentType); before("/*", this::setContentType); before("", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); before("/*", mimeType, apiAuthenticationHelper::checkAdminUserOrGroupAdminUserAnd403); get("", mimeType, this::index); get(Routes.ElasticProfileAPI.ID, mimeType, this::show); get(Routes.ElasticProfileAPI.ID + Routes.ElasticProfileAPI.USAGES, mimeType, this::usages); post("", mimeType, this::create); put(Routes.ElasticProfileAPI.ID, mimeType, this::update); delete(Routes.ElasticProfileAPI.ID, mimeType, this::destroy); exception(RecordNotFoundException.class, this::notFound); }); }
Source:
public Future<AppSearchResult<Void>> setSchema( @NonNull List<AppSearchSchema> schemas, boolean forceOverride) { Callable<AppSearchResult<Void>> callableTask = () -> { SchemaProto.Builder schemaProtoBuilder = SchemaProto.newBuilder(); for (AppSearchSchema schema : schemas) { schemaProtoBuilder.addTypes(schema.getProto()); } mAppSearchImpl.setSchema(schemaProtoBuilder.build(), forceOverride); return AppSearchResult.newSuccessfulResult( null); }; return mExecutor.submit(callableTask); }

Target:
public Future<AppSearchResult<Void>> setSchema( @NonNull List<AppSearchSchema> schemas, boolean forceOverride) { Callable<AppSearchResult<Void>> callableTask = () -> { SchemaProto.Builder schemaProtoBuilder = SchemaProto.newBuilder(); for (AppSearchSchema schema : schemas) { schemaProtoBuilder.addTypes(schema.getProto()); } try { mAppSearchImpl.setSchema(schemaProtoBuilder.build(), forceOverride); return AppSearchResult.newSuccessfulResult( null); } catch (Throwable t) { throw throwableToAppSearchException(t); } }; return mExecutor.submit(callableTask); }
Source:
public Optional<ImmutableZkWorker> findWorkerForTask( final RemoteTaskRunnerConfig config, final ImmutableMap<String, ImmutableZkWorker> zkWorkers, final Task task ) { TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet( new Comparator<ImmutableZkWorker>() { @Override public int compare( ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2 ) { int retVal = Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); if (retVal == 0) { retVal = zkWorker.getWorker().getHost().compareTo(zkWorker2.getWorker().getHost()); } return config.isStrategyTaskAscOrder() ? retVal : -retVal; } } ); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }

Target:
public Optional<ImmutableZkWorker> findWorkerForTask( final RemoteTaskRunnerConfig config, final ImmutableMap<String, ImmutableZkWorker> zkWorkers, final Task task ) { Ordering<ImmutableZkWorker> ordering = new Ordering<ImmutableZkWorker>() { @Override public int compare( ImmutableZkWorker zkWorker, ImmutableZkWorker zkWorker2 ) { int retVal = Ints.compare(zkWorker2.getCurrCapacityUsed(), zkWorker.getCurrCapacityUsed()); if (retVal == 0) { retVal = zkWorker.getWorker().getHost().compareTo(zkWorker2.getWorker().getHost()); } return retVal; } }; TreeSet<ImmutableZkWorker> sortedWorkers = Sets.newTreeSet( config.isStrategyTaskAscOrder() ? ordering : ordering.reverse() ); sortedWorkers.addAll(zkWorkers.values()); final String minWorkerVer = config.getMinWorkerVersion(); for (ImmutableZkWorker zkWorker : sortedWorkers) { if (zkWorker.canRunTask(task) && zkWorker.isValidVersion(minWorkerVer)) { return Optional.of(zkWorker); } } return Optional.absent(); }
Source:
public void testUniqueLayoutData() { GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false); TestFactory factory = TestFactory.newTest().tooltip("toolTip").enabled(false).layoutData(gridDataFactory::create); Label label = factory.create(shell); Label label2 = factory.create(shell); assertNotEquals(label.getLayoutData(), label2.getLayoutData()); }

Target:
public void testUniqueLayoutData() { GridDataFactory gridDataFactory = GridDataFactory.fillDefaults().grab(true, false); TestFactory factory = TestFactory.newTest().layoutData(gridDataFactory::create); Label label = factory.create(shell); Label label2 = factory.create(shell); assertNotSame(label.getLayoutData(), label2.getLayoutData()); }
Source:
protected boolean shouldBeDecorated(final EditPart editPart) { boolean shouldBeDecorated = super.shouldBeDecorated(editPart); return shouldBeDecorated && editPart instanceof IDiagramElementEditPart; }

Target:
protected boolean shouldBeDecorated(final EditPart editPart) { return editPart instanceof IDiagramElementEditPart && super.shouldBeDecorated(editPart); }
Source:
public void shouldThrowStreamsExceptionAtEndIfExceptionDuringSuspend() { expect(active.revokeTasks(revokedTasks, revokedChangelogs)).andReturn(new RuntimeException("")); expect(restoreConsumer.assignment()).andReturn(Collections.emptySet()); replay(); try { taskManager.suspendActiveTasksAndState(revokedPartitions); fail("Should have thrown streams exception"); } catch (final StreamsException e) { } verify(restoreConsumer, active, standby); }

Target:
public void shouldThrowStreamsExceptionAtEndIfExceptionDuringSuspend() { expect(active.suspendOrCloseTasks(revokedTasks, revokedChangelogs)).andReturn(new RuntimeException("")); replay(); try { taskManager.suspendActiveTasksAndState(revokedPartitions); fail("Should have thrown streams exception"); } catch (final StreamsException e) { } verify(restoreConsumer, active, standby); }
Source:
private String formatEntityId(EntityId eid) { final String formattedHBaseRowKey = String.format("hbase=hex:%s", ByteArrayFormatter.toHex(eid.getHBaseRowKey())); if (eid instanceof FormattedEntityId) { final FormattedEntityId feid = (FormattedEntityId) eid; final List<String> components = Lists.newArrayList(); for (Object component: feid.getComponents()) { if (component instanceof Number) { components.add(component.toString()); } else { if (component == null) { components.add("null"); } else { components.add(String.format("'%s'", component)); } } } return String.format("\"[%s]\"", Joiner.on(",").join(components)); } else if (eid instanceof HashedEntityId) { final HashedEntityId hashed = (HashedEntityId) eid; final byte[] kijiRowKey = hashed.getKijiRowKey(); if (kijiRowKey != null) { return String.format("'%s'", Bytes.toString(kijiRowKey)); } } else if (eid instanceof HBaseEntityId) { return formattedHBaseRowKey; } else if (eid instanceof HashPrefixedEntityId) { return String.format("'%s'", Bytes.toString(((HashPrefixedEntityId) eid).getKijiRowKey())); } return formattedHBaseRowKey; }

Target:
private String formatEntityId(EntityId eid) { final String formattedHBaseRowKey = String.format("hbase='%s'", Bytes.toStringBinary(eid.getHBaseRowKey())); if (eid instanceof FormattedEntityId) { final FormattedEntityId feid = (FormattedEntityId) eid; final List<String> components = Lists.newArrayList(); for (Object component: feid.getComponents()) { if (component instanceof Number) { components.add(component.toString()); } else { if (component == null) { components.add("null"); } else { components.add(String.format("'%s'", component)); } } } return String.format("\"[%s]\"", Joiner.on(",").join(components)); } else if (eid instanceof HashedEntityId) { final HashedEntityId hashed = (HashedEntityId) eid; final byte[] kijiRowKey = hashed.getKijiRowKey(); if (kijiRowKey != null) { return String.format("'%s'", Bytes.toString(kijiRowKey)); } return String.format("hbase=hex:%s", ByteArrayFormatter.toHex(eid.getHBaseRowKey())); } else if (eid instanceof HBaseEntityId) { return formattedHBaseRowKey; } else if (eid instanceof HashPrefixedEntityId) { return String.format("'%s'", Bytes.toString(((HashPrefixedEntityId) eid).getKijiRowKey())); } return formattedHBaseRowKey; }
Source:
public File resolve(File dir, String name) { final File abspn = createFile(name); if (abspn.isAbsolute()) return abspn; return createFile(dir, name); }

Target:
public File resolve(File dir, String name) { final File abspn = createFile(name); if (abspn.isAbsolute()) { return abspn; } return createFile(dir, name); }
Source:
static JsonAdapter<?> generatedAdapter(Moshi moshi, Type type, Class<?> rawType) { String adapterClassName = rawType.getName().replace("$", "_") + "JsonAdapter"; try { @SuppressWarnings("unchecked") Class<? extends JsonAdapter<?>> adapterClass = (Class<? extends JsonAdapter<?>>) Class.forName(adapterClassName, true, rawType.getClassLoader()); if (type instanceof ParameterizedType) { return adapterClass.getDeclaredConstructor(Moshi.class, Type[].class) .newInstance(moshi, ((ParameterizedType) type).getActualTypeArguments()); } else { return adapterClass.getDeclaredConstructor(Moshi.class).newInstance(moshi); } } catch (ClassNotFoundException | NoSuchMethodException e) { throw new RuntimeException( "Failed to find the generated the JsonAdapter for " + rawType, e); } catch (IllegalAccessException | InvocationTargetException | InstantiationException e) { throw new RuntimeException( "Failed to create the generated JsonAdapter for " + rawType, e); } }

Target:
static JsonAdapter<?> generatedAdapter(Moshi moshi, Type type, Class<?> rawType) { String adapterClassName = rawType.getName().replace("$", "_") + "JsonAdapter"; try { @SuppressWarnings("unchecked") Class<? extends JsonAdapter<?>> adapterClass = (Class<? extends JsonAdapter<?>>) Class.forName(adapterClassName, true, rawType.getClassLoader()); if (type instanceof ParameterizedType) { Constructor<? extends JsonAdapter<?>> constructor = adapterClass.getDeclaredConstructor(Moshi.class, Type[].class); constructor.setAccessible(true); return constructor.newInstance(moshi, ((ParameterizedType) type).getActualTypeArguments()); } else { Constructor<? extends JsonAdapter<?>> constructor = adapterClass.getDeclaredConstructor(Moshi.class); constructor.setAccessible(true); return constructor.newInstance(moshi); } } catch (ClassNotFoundException e) { throw new RuntimeException( "Failed to find the generated JsonAdapter class for " + rawType, e); } catch (NoSuchMethodException e) { throw new RuntimeException( "Failed to find the generated JsonAdapter constructor for " + rawType, e); } catch (IllegalAccessException e) { throw new RuntimeException( "Failed to access the generated JsonAdapter for " + rawType, e); } catch (InvocationTargetException e) { throw new RuntimeException( "Failed to construct the generated JsonAdapter for " + rawType, e); } catch (InstantiationException e) { throw new RuntimeException( "Failed to instantiate the generated JsonAdapter for " + rawType, e); } }
Source:
public String getMd5(String str) { if (str.length() == 32) { return str; } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } md.update(str.getBytes()); byte b[] = md.digest(); str = byte2hex(b); return str; }

Target:
public static String getMd5(String str) { if (isMD5(str)) { return str; } MessageDigest md = null; try { md = MessageDigest.getInstance("MD5"); } catch (Exception e) { e.printStackTrace(); } md.update(str.getBytes()); byte b[] = md.digest(); str = byte2hex(b); return str; }
Source:
public boolean analyzeJar(Analyzer analyzer) throws Exception { Parameters header = OSGiHeader.parseHeader(analyzer.getProperty(Constants.EXPORT_APIGUARDIAN, "*")); if (header.isEmpty()) return false; Parameters exportPachages = analyzer.getExportPackage(); Instructions instructions = new Instructions(header); Parameters apiGuardianPackages = new Parameters(); for (Clazz c : analyzer.getClassspace() .values()) { if (c.isModule() || c.isInnerClass() || c.isSynthetic()) { continue; } for (Entry<Instruction, Attrs> entry : instructions.entrySet()) { Instruction instruction = entry.getKey(); if (instruction.matches(c.getFQN())) { if (instruction.isNegated()) { break; } if (c.annotations(API_ANNOTATION) .map(ann -> (String) ann.get(STATUS_PROPERTY)) .anyMatch(status -> !INTERNAL_STATUS.equals(status))) { apiGuardianPackages.add(c.getClassName() .getPackageRef() .getFQN(), entry.getValue()); } } } } exportPachages.putAll(apiGuardianPackages); analyzer.setExportPackage(exportPachages.toString()); return false; }

Target:
public boolean analyzeJar(Analyzer analyzer) throws Exception { Parameters header = OSGiHeader.parseHeader(analyzer.getProperty(Constants.EXPORT_APIGUARDIAN)); if (header.isEmpty()) return false; Parameters exportPackages = analyzer.getExportContents(); Instructions instructions = new Instructions(header); Parameters apiGuardianPackages = new Parameters(false); for (Clazz c : analyzer.getClassspace() .values()) { if (c.isModule() || c.isInnerClass() || c.isSynthetic()) { continue; } for (Entry<Instruction, Attrs> entry : instructions.entrySet()) { Instruction instruction = entry.getKey(); if (instruction.matches(c.getFQN())) { if (instruction.isNegated()) { break; } c.annotations(API_ANNOTATION) .map(ann -> Status.valueOf(ann.get(STATUS_PROPERTY))) .max(Status::compareTo) .ifPresent(status -> { Attrs attrs = apiGuardianPackages.computeIfAbsent(c.getClassName() .getPackageRef() .getFQN(), k -> new Attrs(entry.getValue())); attrs.compute(STATUS_PROPERTY, (k, v) -> (v == null) ? status.name() : (Status.valueOf(v) .compareTo(status) > 0 ? v : status.name())); }); } } } apiGuardianPackages.values() .stream() .filter(attrs -> API.Status.valueOf(attrs.get(STATUS_PROPERTY)) == Status.INTERNAL) .forEach(attrs -> { attrs.put(Constants.MANDATORY_DIRECTIVE, STATUS_PROPERTY); attrs.put(Constants.NO_IMPORT_DIRECTIVE, "true"); }); exportPackages.mergeWith(apiGuardianPackages, false); analyzer.setExportContents(exportPackages.toString()); return false; }
Source:
protected Model readModel(String path) { Model model = null; if (path != null) { model = ModelFactory.createDefaultModel(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path); model.read(inputStream, "", "TURTLE"); ResIterator subjects = model.listSubjects(); while (subjects.hasNext()) { Resource subject = subjects.next(); if (subject.isURIResource()) { ResourceUtils.renameResource(subject, ""); break; } } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return model; }

Target:
protected Model readModel(String path) { Model model = null; if (path != null) { model = ModelFactory.createDefaultModel(); InputStream inputStream = getClass().getClassLoader().getResourceAsStream(path); model.read(inputStream, "<LINK_0>", "TURTLE"); Resource subject = model.getResource("<LINK_0>"); if (subject != null) { ResourceUtils.renameResource(subject, ""); } try { inputStream.close(); } catch (IOException e) { e.printStackTrace(); } } return model; }
Source:
public final void onTick(MessageCollector collector, TaskCoordinator coordinator) { onTimer(collector, coordinator); propagateTimer(collector, coordinator); }

Target:
public final void onTick(MessageCollector collector, TaskCoordinator coordinator) { onTimer(collector, coordinator); nextOperators.forEach(sub -> sub.onTick(collector, coordinator)); }
Source:
public ScanRuntimeProvider getScanRuntimeProvider(ScanTableSource.Context runtimeProviderContext) { final DataType rowDataType = schema.toPhysicalRowDataType(); final RowTypeInfo rowTypeInfo = (RowTypeInfo) fromDataTypeToLegacyInfo(rowDataType); final JdbcDynamicInputFormat.Builder builder = JdbcDynamicInputFormat.builder() .setDrivername(options.getDriverName()) .setDBUrl(options.getDbURL()) .setUsername(options.getUsername().orElse(null)) .setPassword(options.getPassword().orElse(null)) .setRowTypeInfo(new RowTypeInfo(rowTypeInfo.getFieldTypes(), rowTypeInfo.getFieldNames())); if (readOptions.getFetchSize() != 0) { builder.setFetchSize(readOptions.getFetchSize()); } final JdbcDialect dialect = options.getDialect(); String query = dialect.getSelectFromStatement( options.getTableName(), rowTypeInfo.getFieldNames(), new String[0]); if (readOptions.getPartitionColumnName().isPresent()) { long lowerBound = readOptions.getPartitionLowerBound().get(); long upperBound = readOptions.getPartitionUpperBound().get(); int numPartitions = readOptions.getNumPartitions().get(); builder.setParametersProvider( new JdbcNumericBetweenParametersProvider(lowerBound, upperBound).ofBatchNum(numPartitions)); query += " WHERE " + dialect.quoteIdentifier(readOptions.getPartitionColumnName().get()) + " BETWEEN ? AND ?"; } builder.setQuery(query); final RowType rowType = RowType.of( Arrays.stream(schema.getFieldDataTypes()) .map(DataType::getLogicalType) .toArray(LogicalType[]::new), schema.getFieldNames()); builder.setRowConverter(dialect.getInputConverter(rowType)); return InputFormatProvider.of(builder.build()); }

Target:
public ScanRuntimeProvider getScanRuntimeProvider(ScanTableSource.Context runtimeProviderContext) { final JdbcRowDataInputFormat.Builder builder = JdbcRowDataInputFormat.builder() .setDrivername(options.getDriverName()) .setDBUrl(options.getDbURL()) .setUsername(options.getUsername().orElse(null)) .setPassword(options.getPassword().orElse(null)); if (readOptions.getFetchSize() != 0) { builder.setFetchSize(readOptions.getFetchSize()); } final JdbcDialect dialect = options.getDialect(); String query = dialect.getSelectFromStatement( options.getTableName(), schema.getFieldNames(), new String[0]); if (readOptions.getPartitionColumnName().isPresent()) { long lowerBound = readOptions.getPartitionLowerBound().get(); long upperBound = readOptions.getPartitionUpperBound().get(); int numPartitions = readOptions.getNumPartitions().get(); builder.setParametersProvider( new JdbcNumericBetweenParametersProvider(lowerBound, upperBound).ofBatchNum(numPartitions)); query += " WHERE " + dialect.quoteIdentifier(readOptions.getPartitionColumnName().get()) + " BETWEEN ? AND ?"; } builder.setQuery(query); final RowType rowType = (RowType) schema.toRowDataType().getLogicalType(); builder.setRowConverter(dialect.getRowConverter(rowType)); builder.setRowDataTypeInfo((TypeInformation<RowData>) runtimeProviderContext .createTypeInformation(schema.toRowDataType())); return InputFormatProvider.of(builder.build()); }
Source:
private <R> R performWithConnection(Function<Object, R> function) { ConnectionSupplier connectionSupplier = getConnectionSupplier(); Object connection = getConnection(connectionSupplier); try { R result = function.apply(connection); connectionSupplier.close(); return result; } catch (Exception e) { if (isFirstPage) { closeDelegate(connection); } extractConnectionException(e).ifPresent(ex -> connectionSupplier.invalidateConnection()); connectionSupplier.invalidateConnection(); throw new MuleRuntimeException(createStaticMessage(COULD_NOT_EXECUTE), e); } }

Target:
private <R> R performWithConnection(Function<Object, R> function) { ConnectionSupplier connectionSupplier = getConnectionSupplier(); Object connection = getConnection(connectionSupplier); try { R result = function.apply(connection); connectionSupplier.close(); return result; } catch (Exception e) { if (isFirstPage) { closeDelegate(connection); } extractConnectionException(e).ifPresent(ex -> connectionSupplier.invalidateConnection()); throw new MuleRuntimeException(createStaticMessage(COULD_NOT_EXECUTE), e); } }