auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Map<Long, Optional<String>> translatePidsToForcedIds(Set<Long> thePids) { Map<Long, Optional<String>> retVal = new HashMap<>(myForcedIdCache.getAllPresent(thePids)); List<Long> remainingPids = thePids .stream() .filter(t -> !retVal.containsKey(t)) .collect(Collectors.toList()); new QueryChunker<Long>().chunk(remainingPids, t->{ List<ForcedId> forcedIds = myForcedIdDao.findAllById(t); for (ForcedId forcedId : forcedIds) { Long nextResourcePid = forcedId.getResourceId(); Optional<String> nextForcedId = Optional.of(forcedId.getForcedId()); retVal.put(nextResourcePid, nextForcedId); myForcedIdCache.put(nextResourcePid, nextForcedId); } }); remainingPids = thePids .stream() .filter(t -> !retVal.containsKey(t)) .collect(Collectors.toList()); <START> for (Long nextResourcePid : remainingPids) { <END> retVal.put(nextResourcePid, Optional.empty()); myForcedIdCache.put(nextResourcePid, Optional.empty()); } return retVal; }</code><technical_language>Nice. This is a elegant manage this cache</technical_language>

Target:
public Map<Long, Optional<String>> translatePidsToForcedIds(Set<Long> thePids) { Map<Long, Optional<String>> retVal = new HashMap<>(myForcedIdCache.getAllPresent(thePids)); List<Long> remainingPids = thePids .stream() .filter(t -> !retVal.containsKey(t)) .collect(Collectors.toList()); new QueryChunker<Long>().chunk(remainingPids, t -> { List<ForcedId> forcedIds = myForcedIdDao.findAllByResourcePid(t); for (ForcedId forcedId : forcedIds) { Long nextResourcePid = forcedId.getResourceId(); Optional<String> nextForcedId = Optional.of(forcedId.getForcedId()); retVal.put(nextResourcePid, nextForcedId); myForcedIdCache.put(nextResourcePid, nextForcedId); } }); remainingPids = thePids .stream() .filter(t -> !retVal.containsKey(t)) .collect(Collectors.toList()); for (Long nextResourcePid : remainingPids) { retVal.put(nextResourcePid, Optional.empty()); myForcedIdCache.put(nextResourcePid, Optional.empty()); } return retVal; }
Source:
<code>private static boolean isValidTransformFunction(FieldSpec fieldSpec) { String column = fieldSpec.getName(); String transformFunction = fieldSpec.getTransformFunction(); if (transformFunction != null) { FunctionEvaluator functionEvaluator = FunctionEvaluatorFactory.getExpressionEvaluator(fieldSpec); <START> if (functionEvaluator != null) { <END> List<String> arguments = functionEvaluator.getArguments(); if (arguments.contains(column)) { LOGGER.error("The arguments of transform function: {}, should not contain the destination column: {}", transformFunction, column); return false; } } } return true; }</code><technical_language>functionEvaluator null</technical_language>

Target:
private static boolean isValidTransformFunction(FieldSpec fieldSpec) { String column = fieldSpec.getName(); String transformFunction = fieldSpec.getTransformFunction(); if (transformFunction != null) { try { List<String> arguments = FunctionEvaluatorFactory.getExpressionEvaluator(fieldSpec).getArguments(); if (arguments.contains(column)) { LOGGER.error("The arguments of transform function: {}, should not contain the destination column: {}", transformFunction, column); return false; } } catch (Exception e) { LOGGER .error("Exception in getting arguments for transform function for column {}", transformFunction, column, e); return false; } } return true; }
Source:
<code>public static <T> Response<T> success(int code, @Nullable T body) { <START> if (code < 200 || code >= 300) throw new IllegalArgumentException("code < 200 or >= 300: " + code); <END> return success(body, new okhttp3.Response.Builder() .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }</code><technical_language>Line long. Please add { } wrapping</technical_language>

Target:
public static <T> Response<T> success(int code, @Nullable T body) { if (code < 200 || code >= 300) { throw new IllegalArgumentException("code < 200 or >= 300: " + code); } return success(body, new okhttp3.Response.Builder() .code(code) .message("Response.success()") .protocol(Protocol.HTTP_1_1) .request(new Request.Builder().url("http://localhost/").build()) .build()); }
Source:
<code>public boolean isAndroidMessage() { for (String platform : platforms) { <START> if (platform.equalsIgnoreCase(PLATFORM_ANDROID)) { <END> return true; } } return false; }</code><technical_language>good if applytrimming for white spaces platform</technical_language>

Target:
public boolean isAndroidMessage() { for (String platform : platforms) { if (platform.trim().equalsIgnoreCase(Platform.ANDROID.key)) { return true; } } return false; }
Source:
<code><START> public void craiIndexInitializationCheck() { <END> final StringBuilder error = new StringBuilder(); if (byteOffsetFromContainer == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its byteOffsetFromContainer is unknown.").append(System.lineSeparator()); } if (containerByteOffset == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its containerByteOffset is unknown.").append(System.lineSeparator()); } if (byteSize == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its byteSize is unknown.").append(System.lineSeparator()); } if (error.length() > 0) { throw new CRAMException(error.toString()); } }</code><technical_language>This private for tests, package-protected/VisibleForTesting. useful separate methods for BAI CRAI validation anyway. subtly (which is hard spot - I thought I them), slice is ready for indexing isn't. fails for BAI CRAI a minor detail - remove a bunch of code test code if consolidated a single method checked for everything</technical_language>

Target:
void craiIndexInitializationCheck() { final StringBuilder error = new StringBuilder(); if (byteOffsetFromContainer == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its byteOffsetFromContainer is unknown.").append(System.lineSeparator()); } if (containerByteOffset == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its containerByteOffset is unknown.").append(System.lineSeparator()); } if (byteSize == UNINITIALIZED_INDEXING_PARAMETER) { error.append("Cannot index this Slice for CRAI because its byteSize is unknown.").append(System.lineSeparator()); } if (error.length() > 0) { throw new CRAMException(error.toString()); } }
Source:
<code>public List<Attribute> getAttributes(PerunSession sess, Member member, Group group, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException { List<Attribute> attributes = getAttributesManagerImpl().getVirtualAttributes(sess, member, group); Iterator<Attribute> attributeIterator = attributes.iterator(); while(attributeIterator.hasNext()) if(attributeIterator.next().getValue() == null) attributeIterator.remove(); attributes.addAll(getAttributesManagerImpl().getAttributes(sess, member, group)); if(workWithUserAttributes) { User user = getPerunBl().getUsersManagerBl().getUserByMember(sess, member); attributes.addAll(getAttributesManagerImpl().getAttributes(sess, user)); <START> attributes.addAll(getAttributesManagerImpl().getAttributes(sess, member)); <END> } return attributes; }</code><technical_language>For workWithUserAttribtues == true returns non-virtual user member attributes. need virtual attributes both. BlImpl instead Impl, need check</technical_language>

Target:
public List<Attribute> getAttributes(PerunSession sess, Member member, Group group, boolean workWithUserAttributes) throws InternalErrorException, WrongAttributeAssignmentException { List<Attribute> attributes = getAttributesManagerImpl().getVirtualAttributes(sess, member, group); Iterator<Attribute> attributeIterator = attributes.iterator(); while(attributeIterator.hasNext()) if(attributeIterator.next().getValue() == null) attributeIterator.remove(); attributes.addAll(getAttributesManagerImpl().getAttributes(sess, member, group)); if(workWithUserAttributes) { User user = getPerunBl().getUsersManagerBl().getUserByMember(sess, member); attributes.addAll(this.getAttributes(sess, user)); attributes.addAll(this.getAttributes(sess, member)); } return attributes; }
Source:
<code>private List<DiskImage> getImagesExcludedFromPreview(List<DiskImage> images, Guid previousActiveSnapshotId, Guid newActiveSnapshotId) { List<DiskImage> excludedImages = new ArrayList<>(); for (DiskImage image : images) { if (((image.getDiskStorageType() == <START> DiskStorageType.IMAGE) || <END> (image.getDiskStorageType() == DiskStorageType.CINDER)) && image.getVmSnapshotId().equals(previousActiveSnapshotId)) { getImageDao().updateImageVmSnapshotId(image.getImageId(), newActiveSnapshotId); excludedImages.add(image); } } return excludedImages; }</code><technical_language>worth some generic method for checking 'IMAGE || CINDER'.. in DiskStorageType? isSnappableStorageType somewhere? :)</technical_language>

Target:
private List<DiskImage> getImagesExcludedFromPreview(List<DiskImage> images, Guid previousActiveSnapshotId, Guid newActiveSnapshotId) { List<DiskImage> excludedImages = new ArrayList<>(); for (DiskImage image : images) { if (image.isStorageTypeSupportsSnapshot() && image.getVmSnapshotId().equals(previousActiveSnapshotId)) { getImageDao().updateImageVmSnapshotId(image.getImageId(), newActiveSnapshotId); excludedImages.add(image); } } return excludedImages; }
Source:
<code>public void process(JSONRequestContext jsonRequestContext) { StudentGroupContactLogEntryDAO logEntryDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryDAO(); StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); try { <START> Long entryId = jsonRequestContext.getLong("entryId"); <END> StudentGroupContactLogEntry entry = logEntryDAO.findById(entryId); String commentText = jsonRequestContext.getRequest().getParameter("commentText"); String commentCreatorName = jsonRequestContext.getRequest().getParameter("commentCreatorName"); Date commentDate = new Date(NumberUtils.createLong(jsonRequestContext.getRequest().getParameter("commentDate"))); StudentGroupContactLogEntryComment comment = entryCommentDAO.create(entry, commentText, commentDate, commentCreatorName); Map<String, Object> info = new HashMap<String, Object>(); info.put("id", comment.getId()); info.put("creatorName", comment.getCreatorName()); info.put("timestamp", comment.getCommentDate().getTime()); info.put("text", comment.getText()); info.put("entryId", entryId); jsonRequestContext.addResponseParameter("results", info); } catch (Exception e) { throw new SmvcRuntimeException(e); } }</code><technical_language>Null-check</technical_language>

Target:
public void process(JSONRequestContext jsonRequestContext) { StudentGroupContactLogEntryDAO logEntryDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryDAO(); StudentGroupContactLogEntryCommentDAO entryCommentDAO = DAOFactory.getInstance().getStudentGroupContactLogEntryCommentDAO(); Long entryId = jsonRequestContext.getLong("entryId"); if (entryId == null) throw new SmvcRuntimeException(StatusCode.UNDEFINED, "EntryId was not defined."); try { StudentGroupContactLogEntry entry = logEntryDAO.findById(entryId); String commentText = jsonRequestContext.getString("commentText"); String commentCreatorName = jsonRequestContext.getString("commentCreatorName"); Date commentDate = jsonRequestContext.getDate("commentDate"); StudentGroupContactLogEntryComment comment = entryCommentDAO.create(entry, commentText, commentDate, commentCreatorName); Map<String, Object> info = new HashMap<String, Object>(); info.put("id", comment.getId()); info.put("creatorName", comment.getCreatorName()); info.put("timestamp", comment.getCommentDate() != null ? comment.getCommentDate().getTime() : ""); info.put("text", comment.getText()); info.put("entryId", entryId); jsonRequestContext.addResponseParameter("results", info); } catch (Exception e) { throw new SmvcRuntimeException(e); } }
Source:
<code>public void testExecuteAndPostProcess() { gaeSimulation.loginAsInstructor("idOfInstructor3"); ______TS("typical success case"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "idOfTypicalCourse1" }; InstructorCourseInstructorCopyPageAction action = getAction(submissionParams); ShowPageResult result = getShowPageResult(action); String expectedString = getPageResultDestination( Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, false, "idOfInstructor3"); assertEquals(expectedString, result.getDestinationWithParams()); assertTrue(result.getStatusMessage().isEmpty()); ______TS("failure: non-existent course"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "INVALID COURSE" }; action = getAction(submissionParams); try { result = getShowPageResult(action); signalFailureToDetectException(); } catch (UnauthorizedAccessException uae) { assertEquals("Trying to access system using a non-existent instructor entity", uae.getMessage()); } <START> ______TS("failure: unsufficient permissions"); <END> gaeSimulation.loginAsInstructor(typicalBundle.accounts.get("helperOfCourse1").googleId); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "idOfTypicalCourse1" }; action = getAction(submissionParams); try { result = getShowPageResult(action); signalFailureToDetectException(); } catch (UnauthorizedAccessException uae) { assertEquals("Course [idOfTypicalCourse1] is not accessible to instructor [helper@course1.tmt] " + "for privilege [canmodifyinstructor]", uae.getMessage()); } }</code><technical_language>I "unsufficient" is in use. "insufficient"</technical_language>

Target:
public void testExecuteAndPostProcess() { gaeSimulation.loginAsInstructor("idOfInstructor3"); ______TS("typical success case"); String[] submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "idOfTypicalCourse1" }; InstructorCourseInstructorCopyPageAction action = getAction(submissionParams); ShowPageResult result = getShowPageResult(action); String expectedString = getPageResultDestination( Const.ViewURIs.INSTRUCTOR_COURSE_INSTRUCTOR_COPY_MODAL, false, "idOfInstructor3"); assertEquals(expectedString, result.getDestinationWithParams()); assertTrue(result.getStatusMessage().isEmpty()); ______TS("failure: non-existent course"); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "INVALID COURSE" }; action = getAction(submissionParams); try { result = getShowPageResult(action); signalFailureToDetectException(); } catch (UnauthorizedAccessException uae) { assertEquals("Trying to access system using a non-existent instructor entity", uae.getMessage()); } ______TS("failure: insufficient permissions"); gaeSimulation.loginAsInstructor(typicalBundle.accounts.get("helperOfCourse1").googleId); submissionParams = new String[] { Const.ParamsNames.COURSE_ID, "idOfTypicalCourse1" }; action = getAction(submissionParams); try { result = getShowPageResult(action); signalFailureToDetectException(); } catch (UnauthorizedAccessException uae) { assertEquals("Course [idOfTypicalCourse1] is not accessible to instructor [helper@course1.tmt] " + "for privilege [canmodifyinstructor]", uae.getMessage()); } }
Source:
<code>public void start() { log.info( "Opening connection to MongoDB instance" ); try { Object cfgHost = this.cfg.get( "hibernate.ogm.mongo.host" ); String host = cfgHost != null ? cfgHost.toString() : DEFAULT_HOST; Object cfgPort = this.cfg.get( "hibernate.ogm.mongo.port" ); int port = cfgPort != null ? Integer.valueOf( cfgPort.toString() ).intValue() : DEFAULT_PORT; log.tracef( "Opening connection to: %1$s : %1$s", host, String.valueOf( port ) ); this.mongo = new Mongo( host, port ); } catch ( UnknownHostException e ) { <START> throw new HibernateException( "The database host cannot be resolved", e ); <END> } catch ( MongoException e ) { throw new HibernateException( "Cannot open the MongoDB connection", e ); } }</code><technical_language>above, exceptions Log interface generated</technical_language>

Target:
public void start() { if ( !isCacheProvided ) { log.info( "Opening connection to MongoDB instance" ); try { Object cfgHost = this.cfg.get( "hibernate.ogm.mongo.host" ); String host = cfgHost != null ? cfgHost.toString() : DEFAULT_HOST; int port = DEFAULT_PORT; Object cfgPort = this.cfg.get( "hibernate.ogm.mongo.port" ); if ( cfgPort != null ) { try { int temporaryPort = Integer.valueOf( cfgPort.toString() ).intValue(); if ( temporaryPort < 1 || temporaryPort > 65535 ) { throw new HibernateException( "The value set for the hibernate.ogm.mongo.port property must be between 1 and 65535" ); } port = temporaryPort; } catch ( NumberFormatException e ) { throw new HibernateException( "The value set for the hibernate.ogm.mongo.port is not a number" ); } } if ( log.isTraceEnabled() ) { log.tracef( "Opening connection to: %1$s : %1$s", host, String.valueOf( port ) ); } this.mongo = new Mongo( host, port ); this.isCacheProvided = true; } catch ( UnknownHostException e ) { throw new HibernateException( "The database host cannot be resolved", e ); } catch ( RuntimeException e ) { log.unableToInitializeMongoDB( e ); } } }
Source:
<code>protected String sendGetToElectricity(String query) { Uri.Builder uriBuilder = Uri.parse(BASE_URL_ELECTRICITY).buildUpon(); uriBuilder.encodedQuery(query); Uri uri = uriBuilder.build(); try { URL url = new URL(uri.toString()); <START> return ApiConnection.getResponseFromHttpConnection(url); <END> } catch (MalformedURLException e) { e.printStackTrace(); } return null; }</code><technical_language># This fail longer sending authorization, line 43 in deleted section. tests (that migrated unit test suite) failing</technical_language>

Target:
protected String sendGetToElectricity(String query) { Uri.Builder uriBuilder = Uri.parse(BASE_URL_ELECTRICITY).buildUpon(); uriBuilder.encodedQuery(query); uriBuilder.appendQueryParameter("Authorization", AUTHORIZATION); Uri uri = uriBuilder.build(); try { URL url = new URL(uri.toString()); Map.Entry<String, String> authorizationProperty = new Map.Entry<String, String>() { @Override public String getKey() { return "Authorization"; } @Override public String getValue() { return AUTHORIZATION; } @Override public String setValue(String object) { return null; } }; return ApiConnection.getResponseFromHttpConnection(url, authorizationProperty); } catch (MalformedURLException e) { e.printStackTrace(); } return null; }
Source:
<code>RunConfiguration getRunConfiguration(MatrixBuildExecution context) throws IOException { RunConfiguration runConfig = new RunConfiguration(); try { <START> buildLock.writeLock().lock(); <END> runConfig.config = rebuildConfigurations(context); runConfig.axisList = (AxisList) Jenkins.XSTREAM.fromXML(Jenkins.XSTREAM.toXML(axes)); } finally { buildLock.writeLock().unlock(); } return runConfig; }</code><technical_language>I understand this provides week concurrency guarantee protects 2 concurrent dynamic builds dynamic build and, say, config update. Is ok for you</technical_language>

Target:
RunConfiguration getRunConfiguration(MatrixBuildExecution context) throws IOException { RunConfiguration runConfig = new RunConfiguration(); try { buildLock.lock(); runConfig.config = rebuildConfigurations(context); runConfig.axisList = (AxisList) Jenkins.XSTREAM.fromXML(Jenkins.XSTREAM.toXML(axes)); } finally { buildLock.unlock(); } return runConfig; }
Source:
<code>public File writeClassCode(String packageName, String classname, String classCode) throws RandoopOutputException { File testFile = javaFileWriter.writeClassCode(packageName, classname, classCode); try { Minimize.mainMinimize( testFile, Minimize.suiteclasspath, Minimize.testsuitetimeout, Minimize.verboseminimizer); } catch (IOException e) { <START> System.err.println("IOException: " + e.getMessage()); <END> e.printStackTrace(); throw new RandoopOutputException( "Couldn't output minimized test suite due to an IOException."); } return testFile; }</code><technical_language>printed stack trace next line contains message type, this line neede</technical_language>

Target:
public File writeClassCode(String packageName, String classname, String classCode) throws RandoopOutputException { File testFile = javaFileWriter.writeClassCode(packageName, classname, classCode); try { Minimize.mainMinimize( testFile, Minimize.suiteclasspath, Minimize.testsuitetimeout, Minimize.verboseminimizer); } catch (IOException e) { throw new RandoopOutputException(e); } return testFile; }
Source:
<code>public Void execute() throws GitException { remote = remote == null ? "origin" : remote; reset(); commandLine.add("pull"); if (remote != null) { commandLine.add(remote); } if (refSpec != null) { commandLine.add(refSpec); } if (author != null) { Map<String, String> environment = new HashMap<>(); environment.put("GIT_AUTHOR_NAME", author.getName()); environment.put("GIT_AUTHOR_EMAIL", author.getEmail()); environment.put("GIT_COMMITTER_NAME", author.getName()); environment.put("GIT_COMMITTER_EMAIL", author.getEmail()); setCommandEnvironment(environment); } start(); pullResponse = DtoFactory.getInstance().createDto(PullResponse.class); if (lines.getLast().startsWith("Already")) { pullResponse.setAlreadyUpToDate(true); pullResponse.setCommandOutput(lines.getLast()); } else { pullResponse.setAlreadyUpToDate(false); Joiner joiner = Joiner.on("\n"); <START> pullResponse.setCommandOutput(joiner.join(lines.listIterator())); <END> } return null; }</code><technical_language>line</technical_language>

Target:
public Void execute() throws GitException { remote = remote == null ? "origin" : remote; reset(); commandLine.add("pull"); if (remote != null) { commandLine.add(remote); } if (refSpec != null) { commandLine.add(refSpec); } if (author != null) { Map<String, String> environment = new HashMap<>(); environment.put("GIT_AUTHOR_NAME", author.getName()); environment.put("GIT_AUTHOR_EMAIL", author.getEmail()); environment.put("GIT_COMMITTER_NAME", author.getName()); environment.put("GIT_COMMITTER_EMAIL", author.getEmail()); setCommandEnvironment(environment); } start(); pullResponse = newDto(PullResponse.class).withCommandOutput(Joiner.on("\n").join(lines)); return null; }
Source:
<code>public Object clone( ClassLoader target ) { try { <START> Class<?> cls = target.loadClass( getClass().getName() ); <END> Object clone = cls.newInstance(); cls.getMethod( "setDisable", boolean.class ) .invoke( clone, isDisable() ); cls.getMethod( "setVersion", String.class ) .invoke( clone, getVersion() ); return clone; } catch ( ReflectiveOperationException e ) { throw new IllegalStateException( e.getLocalizedMessage() ); } }</code><technical_language>do duplicate this code ? introducing some protected utility method</technical_language>

Target:
public Object clone( ClassLoader target ) { try { Class<?> cls = ReflectionUtils.reloadClass( target, this ); Object clone = cls.newInstance(); cls.getMethod( "setDisable", boolean.class ) .invoke( clone, isDisable() ); cls.getMethod( "setVersion", String.class ) .invoke( clone, getVersion() ); return clone; } catch ( ReflectiveOperationException e ) { throw new IllegalStateException( e.getLocalizedMessage() ); } }
Source:
<code>public void afterRefreshTreatment(boolean succeeded) { if (!succeeded) { lockManager.releaseLock(monitoringLock); return; } Guid storagePoolId = null; ArrayList<VDSDomainsData> domainsList = null; try { synchronized (this) { unrespondedAttempts.set(0); setLastUpdate(); try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); domainsList = cachedVds.getDomains(); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); if (domainsList != null) { updateVdsDomainsData(cachedVds, storagePoolId, domainsList); <START> } <END> } }</code><technical_language>code, move code synchronized block, try/catch block releasing lock</technical_language>

Target:
public void afterRefreshTreatment(boolean succeeded) { if (!succeeded) { lockManager.releaseLock(monitoringLock); return; } try { Guid storagePoolId = null; ArrayList<VDSDomainsData> domainsList = null; synchronized (this) { unrespondedAttempts.set(0); setLastUpdate(); try { hostMonitoring.afterRefreshTreatment(); if (cachedVds != null && cachedVds.getStatus() != VDSStatus.Maintenance) { storagePoolId = cachedVds.getStoragePoolId(); domainsList = cachedVds.getDomains(); } hostMonitoring = null; } catch (IRSErrorException ex) { logAfterRefreshFailureMessage(ex); if (log.isDebugEnabled()) { logException(ex); } } catch (RuntimeException ex) { logAfterRefreshFailureMessage(ex); logException(ex); } } if (domainsList != null) { updateVdsDomainsData(cachedVds, storagePoolId, domainsList); } } catch (Exception e) { log.error("Timer update runtime info failed. Exception:", ExceptionUtils.getRootCauseMessage(e)); log.debug("Exception:", e); } finally { lockManager.releaseLock(monitoringLock); } }
Source:
<code>private void killInstances(SchedulerDriver driver, int toKill) { if (toKill == 0) return; if (toKill == crateInstances.size()) { markForceShutdown(driver); } int killed = 0; LOGGER.debug("Too many instances running. Killing tasks", toKill); for (CrateInstance crateInstance : crateInstances) { if (killed == toKill) { break; } LOGGER.info("Kill task {}", crateInstance.taskId()); <START> stateStore.state().addSlaveWithInstance(crateInstance.slaveID()); <END> driver.killTask(taskID(crateInstance.taskId())); killed++; } }</code><technical_language>this happen "force shutdown"</technical_language>

Target:
private void killInstances(SchedulerDriver driver, int toKill) { if (toKill == 0) return; if (toKill == crateInstances.size()) { markForceShutdown(driver); } int killed = 0; LOGGER.debug("Too many instances running. Killing tasks", toKill); for (CrateInstance crateInstance : crateInstances) { if (killed == toKill) { break; } LOGGER.info("Kill task {}", crateInstance.taskId()); driver.killTask(taskID(crateInstance.taskId())); killed++; } }
Source:
<code>@Before public void setUp() throws IOException { <START> file = File.createTempFile("test.foq", null); <END> file.delete(); queue = new FileObjectQueue<String>(file, new SerializedConverter<String>()); queue.add("one"); queue.add("two"); queue.add("three"); }</code><technical_language>TemporaryFolder rule simplifies this new File(tempFolder.get(), "queueueueueu")</technical_language>

Target:
@Before public void setUp() throws IOException { File parent = folder.getRoot(); File file = new File(parent, "queue-file"); queue = new FileObjectQueue<String>(file, new SerializedConverter<String>()); queue.add("one"); queue.add("two"); queue.add("three"); }
Source:
<code>public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result = Collections.emptyList(); <START> Block figureBlock = context.getCurrentMacroBlock().getFirstBlock(new BlockMatcher() <END> { @Override public boolean match(Block block) { return block instanceof FigureBlock; } }, Block.Axes.ANCESTOR); if (figureBlock != null) { XDOM xdom = this.contentParser.parse(content, context, false, false); List<Block> figureCaptionChildren = xdom.getChildren(); this.parserUtils.removeTopLevelParagraph(figureCaptionChildren); List<Block> contentBlock = Collections.singletonList(new FigureCaptionBlock(figureCaptionChildren)); result = Collections.singletonList(new MetaDataBlock(contentBlock, this.getUnchangedContentMetaData())); } return result; }</code><technical_language>Note is a ClassBlockMatcher pass FigureBlock.class. a static field instead of recreate matcher time</technical_language>

Target:
public List<Block> execute(Object unusedParameters, String content, MacroTransformationContext context) throws MacroExecutionException { List<Block> result = Collections.emptyList(); Block parent = context.getCurrentMacroBlock().getParent(); if (parent instanceof FigureBlock) { XDOM xdom = this.contentParser.parse(content, context, false, false); List<Block> figureCaptionChildren = xdom.getChildren(); this.parserUtils.removeTopLevelParagraph(figureCaptionChildren); figureCaptionChildren = Collections.singletonList(new FigureCaptionBlock(figureCaptionChildren)); result = Collections.singletonList(new MetaDataBlock(figureCaptionChildren, getUnchangedContentMetaData())); } return result; }
Source:
<code>private static PrintStream printTime(long start, long end) { <START> return System.out.format(", %.3f", 0.000000001 * (end - start)); <END> }</code><technical_language>add a text show output means. know, running this benchmark, need more verbose ;-)</technical_language>

Target:
private static void printTime(long start, long end) { System.out.format(", %.3f", 0.000000001 * (end - start)); }
Source:
<code>public static Configuration configurePythonDependencies( List<Tuple2<String, DistributedCache.DistributedCacheEntry>> cachedFiles, Configuration config) { PythonDependencyManager pythonDependencyManager = new PythonDependencyManager(cachedFiles, config); <START> pythonDependencyManager.configure(config); <END> return pythonDependencyManager.getConfigWithPythonDependencyOptions(); }</code><technical_language>call method configure in constructor of PythonDependencyManager</technical_language>

Target:
public static Configuration configurePythonDependencies( List<Tuple2<String, DistributedCache.DistributedCacheEntry>> cachedFiles, Configuration config) { PythonDependencyManager pythonDependencyManager = new PythonDependencyManager(cachedFiles, config); return pythonDependencyManager.getConfigWithPythonDependencyOptions(); }
Source:
<code>private ClusterConfig.Builder clusterConfigBuilder(ServiceDiscoveryConfig config) { Builder builder = ClusterConfig.builder(); if (config.seeds() != null) { builder.seedMembers( Arrays.stream(config.seeds()) <START> .map(address -> Address.create(address.host(), address.port())) <END> .toArray(Address[]::new)); } if (config.port() != null) { builder.port(config.port()); } if (config.tags() != null) { builder.metadata(config.tags()); } if (config.memberHost() != null) { builder.memberHost(config.memberHost()); } if (config.memberPort() != null) { builder.memberPort(config.memberPort()); } return builder; }</code><technical_language>u mind if I ask u fully Address type here. in sync line 48</technical_language>

Target:
private ClusterConfig.Builder clusterConfigBuilder(ServiceDiscoveryConfig config) { Builder builder = ClusterConfig.builder(); if (config.seeds() != null) { builder.seedMembers( Arrays.stream(config.seeds()) .map(address -> io.scalecube.transport.Address.create(address.host(), address.port())) .toArray(io.scalecube.transport.Address[]::new)); } if (config.port() != null) { builder.port(config.port()); } if (config.tags() != null) { builder.metadata(config.tags()); } if (config.memberHost() != null) { builder.memberHost(config.memberHost()); } if (config.memberPort() != null) { builder.memberPort(config.memberPort()); } return builder; }
Source:
<code>private List<IRecord> remove(BrowserAction action) { List<IRecord> records = new LinkedList<IRecord>(); ElementRecord element = getElement(action.getID()); if (element == null) return new LinkedList<IRecord>(); <START> records.add(element.getRemoveRecord()); <END> return records; }</code><technical_language><LINK_0></technical_language>

Target:
private List<IRecord> remove(BrowserAction action) { ElementRecord element = getElement(action.getID()); if (element == null) return Collections.emptyList(); List<IRecord> records = new ArrayList<IRecord>(); records.add(element.getRemoveRecord()); return records; }
Source:
<code>public Workflow getWorkflow(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "workflow ID", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "Comma-delimited list of fields to include: validations") @QueryParam("include") String include) { Workflow workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkCanRead(user, workflow); Hibernate.initialize(workflow.getUsers()); <START> if (checkIncludes(include, "validations")) { <END> workflow.getVersions().forEach(workflowVersion -> Hibernate.initialize(workflowVersion.getValidations())); } return workflow; }</code><technical_language>This block is in this file 4 times. I recommend making a constant out of "validations", and/or creating a method avoid duplication</technical_language>

Target:
public Workflow getWorkflow(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "workflow ID", required = true) @PathParam("workflowId") Long workflowId, @ApiParam(value = "Comma-delimited list of fields to include: validations") @QueryParam("include") String include) { Workflow workflow = workflowDAO.findById(workflowId); checkEntry(workflow); checkCanRead(user, workflow); Hibernate.initialize(workflow.getUsers()); initializeValidations(include, workflow); return workflow; }
Source:
<code>public void getSystemInfo(final OnReceiveSystemInfoListener listener) { new GetTask(mHttpsCertPath) { @Override protected void onPostExecute(String s) { if (s == null) return; try { JSONObject system = new JSONObject(s); SystemInfo si = new SystemInfo(); si.alloc = system.getLong("alloc"); si.cpuPercent = system.getDouble("cpuPercent"); <START> if system.has("discoveryEnabled") { <END> si.extAnnounceTotal = system.getInt("discoveryMethods"); si.extAnnounceConnected = si.extAnnounceTotal - system.getJSONObject("discoveryErrors").length(); } else { si.extAnnounceTotal = 0; si.extAnnounceConnected = 0; } si.goroutines = system.getInt("goroutines"); si.myID = system.getString("myID"); si.sys = system.getLong("sys"); listener.onReceiveSystemInfo(si); } catch (JSONException e) { Log.w(TAG, "Failed to read system info", e); } } }.execute(mUrl, GetTask.URI_SYSTEM, mApiKey); }</code><technical_language>Java requires parentheses if condition: if (system.has("discoveryEnabled")). Add merge ;)</technical_language>

Target:
public void getSystemInfo(final OnReceiveSystemInfoListener listener) { new GetTask(mHttpsCertPath) { @Override protected void onPostExecute(String s) { if (s == null) return; try { JSONObject system = new JSONObject(s); SystemInfo si = new SystemInfo(); si.alloc = system.getLong("alloc"); si.cpuPercent = system.getDouble("cpuPercent"); if (system.has("discoveryEnabled")) { si.extAnnounceTotal = system.getInt("discoveryMethods"); si.extAnnounceConnected = si.extAnnounceTotal - system.getJSONObject("discoveryErrors").length(); } else { si.extAnnounceTotal = 0; si.extAnnounceConnected = 0; } si.goroutines = system.getInt("goroutines"); si.myID = system.getString("myID"); si.sys = system.getLong("sys"); listener.onReceiveSystemInfo(si); } catch (JSONException e) { Log.w(TAG, "Failed to read system info", e); } } }.execute(mUrl, GetTask.URI_SYSTEM, mApiKey); }
Source:
<code>public static RetryOptions getDefaultOptions() { <START> return new Builder().build(); <END> }</code><technical_language>This builder().build() instead of new Builder().build()</technical_language>

Target:
public static RetryOptions getDefaultOptions() { return builder().build(); }
Source:
<code>Node(final String name, final NodeProcessor nodeProcessor, final Dag dag) { requireNonNull(nodeProcessor, "The nodeProcessor parameter can't be null."); this.nodeProcessor = nodeProcessor; requireNonNull(name, "The name of the node can't be null"); this.name = name; <START> requireNonNull(name, "The dag of the node can't be null"); <END> this.dag = dag; }</code><technical_language>small typo - I name is supposed dag, right</technical_language>

Target:
Node(final String name, final NodeProcessor nodeProcessor, final Dag dag) { requireNonNull(nodeProcessor, "The nodeProcessor parameter can't be null."); this.nodeProcessor = nodeProcessor; requireNonNull(name, "The name of the node can't be null"); this.name = name; requireNonNull(dag, "The dag of the node can't be null"); this.dag = dag; }
Source:
<code><START> public String getHadoopVersion() { <END> return hadoopVersion; }</code><technical_language>This simply return enum</technical_language>

Target:
public HadoopVersion getHadoopVersion() { return hadoopVersion; }
Source:
<code>private static boolean checkPolicyProviderRemoved(OperationContext context, String defaultPolicy, ModelNode newValue, ModelNode oldValue) throws OperationFailedException { List<String> newPolicies = getPoliciesNames(context, newValue); List<String> oldPolicies = getPoliciesNames(context, oldValue); <START> return oldPolicies.contains(defaultPolicy) && !newPolicies.contains(defaultPolicy); <END> }</code><technical_language>Nit: point computing newPolicies if !oldPolicies.contains(defaultPolicy)</technical_language>

Target:
private static boolean checkPolicyProviderRemoved(OperationContext context, String defaultPolicy, ModelNode newValue, ModelNode oldValue) throws OperationFailedException { if (getPoliciesNames(context, oldValue).contains(defaultPolicy)) { return !getPoliciesNames(context, newValue).contains(defaultPolicy); } return false; }
Source:
<code>private boolean saveFileToExternalStorage() { mArcGISTempFolderPath = Environment.getExternalStorageDirectory() + File.separator + this.getResources() .getString(R.string.pin_blank_orange_folder_name); mPinBlankOrangeFilePath = mArcGISTempFolderPath + File.separator + this.getResources().getString(R.string.pin_blank_orange_file_name); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pin_blank_orange); File folder = new File(mArcGISTempFolderPath); <START> folder.mkdirs(); <END> File file = new File(mPinBlankOrangeFilePath); try { OutputStream outStream = new FileOutputStream(file); bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); return true; } catch (Exception e) { Log.e("picture-marker-symbol", "Failed to write image to external directory: message = " + e.getMessage()); return false; } }</code><technical_language>Result is ignored, test result log if successful send toast message if fails. do similar in onDestroy log result</technical_language>

Target:
private boolean saveFileToExternalStorage() { mArcGISTempFolderPath = Environment.getExternalStorageDirectory() + File.separator + this.getResources() .getString(R.string.pin_blank_orange_folder_name); mPinBlankOrangeFilePath = mArcGISTempFolderPath + File.separator + this.getResources().getString(R.string.pin_blank_orange_file_name); Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.pin_blank_orange); File folder = new File(mArcGISTempFolderPath); if(folder.mkdirs()){ Log.d(TAG, "Temp folder created"); }else{ Toast.makeText(MainActivity.this, "Could not create temp folder", Toast.LENGTH_LONG).show(); } File file = new File(mPinBlankOrangeFilePath); try { OutputStream outStream = new FileOutputStream(file); bm.compress(Bitmap.CompressFormat.PNG, 100, outStream); outStream.flush(); outStream.close(); return true; } catch (Exception e) { Log.e("picture-marker-symbol", "Failed to write image to external directory: message = " + e.getMessage()); return false; } }
Source:
<code>private void doTaskStart() { if(!started) { List<String> args = new ArrayList<>(0); if(this.applicationArguments != null) { args = Arrays.asList(this.applicationArguments.getSourceArgs()); } <START> this.taskExecution = this.taskRepository.createTaskExecution(this.taskRepository.getNextExecutionId(), <END> this.taskNameResolver.getTaskName(), new Date(), args); } else { logger.error("Multiple start events have been received. The first one was " + "recorded."); } taskExecution.setExitMessage(invokeOnTaskStartup(taskExecution).getExitMessage()); }</code><technical_language>create, providing id? is encapsulated create call</technical_language>

Target:
private void doTaskStart() { if(!started) { List<String> args = new ArrayList<>(0); if(this.applicationArguments != null) { args = Arrays.asList(this.applicationArguments.getSourceArgs()); } this.taskExecution = this.taskRepository.createTaskExecution( this.taskNameResolver.getTaskName(), new Date(), args); } else { logger.error("Multiple start events have been received. The first one was " + "recorded."); } taskExecution.setExitMessage(invokeOnTaskStartup(taskExecution).getExitMessage()); }
Source:
<code>private void execute(Callable<Void> task) throws IOException { try { <START> copier.submit(task).get(); <END> } catch (InterruptedException e) { throw interrupted(e); } catch (RejectedExecutionException e) { throw new IOException(e); } catch (ExecutionException e) { throw new IOException(e.getCause()); } }</code><technical_language>Nevermind, I is Future.get() throws InterruptedException</technical_language>

Target:
private void execute(Callable<Void> task) throws IOException { if (pending != null) { checkedGet(pending); } try { pending = copier.submit(task); } catch (RejectedExecutionException e) { throw new IOException(e); } checkedGet(pending); pending = null; }
Source:
<code>private void closeWindowAction() { <START> Window window = windowClose.getScene().getWindow(); <END> if (window instanceof Stage) { Stage stage = (Stage) window; stage.close(); } }</code><technical_language>Duplicate code, obtaining Stage a method</technical_language>

Target:
private void closeWindowAction() { getStage(windowClose.getScene().getWindow()).close(); }
Source:
<code>public void start() { try { String hostName = "localhost"; log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @Override public void onMessageReceived(byte[] message) { try { JsonRpcRequest request = JsonRpcRequest.fromJsonNode(mapper.readTree(message)); ObjectNode parameters = mapper.createObjectNode(); ContextHolder.init(); ContextHolder.setServerName(client.getHostname()); if (request.getMethod().equalsIgnoreCase("Host.getCapabilities")) { Map response = api.getVdsCapabilities(); parameters.putPOJO("info", response); } JsonRpcResponse response = new JsonRpcResponse(parameters, null, request.getId()); client.sendMessage(fromJson(response)); } catch (IOException e) { log.error("Failure in processing request", e); } } }); } }); Thread t = new Thread(new Runnable() { <START> <END> @Override public void run() { while (true) { try { futureListener.get(); } catch (Exception e) { log.error("Error while waiting on listener", e); } } } }); t.start(); } catch (Exception e) { log.error("Failure to start json server socket", e); } }</code><technical_language>Selector thread is for opening port. need wait some time get actual listener. easy stop listener close this thread. do want resource leaks</technical_language>

Target:
public void start() { try { String hostName = "localhost"; log.debug("Opening a Stomp server " + hostName + ":" + jsonPort); Reactor reactor = ReactorFactory.getReactor(null, ReactorType.STOMP); final Future<ReactorListener> futureListener = reactor.createListener(hostName, jsonPort, new ReactorListener.EventListener() { @Override public void onAcccept(final ReactorClient client) { client.addEventListener(new MessageListener() { @SuppressWarnings("unchecked") @Override public void onMessageReceived(byte[] message) { try { JsonRpcRequest request = JsonRpcRequest.fromJsonNode(mapper.readTree(message)); ContextHolder.init(); ContextHolder.setServerName(client.getHostname()); ResponseBuilder builder = new ResponseBuilder(request.getId()); String methodName = request.getMethod(); if (apiMapper.containsKey(methodName)) { Method m = apiMapper.get(methodName); Class<?>[] params = m.getParameterTypes(); Map<?, ?> response = null; if (params == null || params.length == 0) { response = (Map<?, ?>) m.invoke(api); } else { response = (Map<?, ?>) m.invoke(api, request.getParams()); } builder = builder.withResult((Map<String, Object>) response.get("info")); } else { log.error("Unsupported method " + methodName); builder = builder.withError((Map<String, Object>) Collections.EMPTY_MAP); } JsonRpcResponse response = builder.build(); client.sendMessage(fromJson(response)); } catch (Throwable e) { log.error("Failure in processing request", e); } } }); } }); listener = futureListener.get(TIMEOUT, TimeUnit.MILLISECONDS); } catch (Exception e) { log.error("Failure to start json server socket", e); } }
Source:
<code><START> public Map<SystemStreamPartition, Startpoint> getFanOutForTask(TaskName taskName) { <END> Preconditions.checkState(!stopped, "Underlying metadata store not available"); Preconditions.checkNotNull(taskName, "TaskName cannot be null"); StartpointFanOut.StartpointFanOutSerde startpointFanOutSerde = new StartpointFanOut.StartpointFanOutSerde(); byte[] fanOutBytes = fanOutStore.get(toFanOutStoreKey(taskName)); if (ArrayUtils.isEmpty(fanOutBytes)) { return null; } StartpointFanOut startpointFanOut = startpointFanOutSerde.fromBytes(fanOutBytes); return ImmutableMap.copyOf(startpointFanOut.getFanOuts()); }</code><technical_language>3 "clients" for startpoints stores: 1) startpoint tool (write non-fanout store) 2) job coordinator (read/write non-fanout store, write fanout store) 3) processing containers (read/write fanout store) good separate out categories classes? need construct full StartpointManager for everything. main benefit I this is easier construct dependencies for stage. non-ideal pattern in Samza I observed is object is for flows, of dependencies for object needed, if flow dependency. Do possible/helpful avoid pattern here</technical_language>

Target:
public Map<SystemStreamPartition, Startpoint> getFanOutForTask(TaskName taskName) throws IOException { Preconditions.checkState(!stopped, "Underlying metadata store not available"); Preconditions.checkNotNull(taskName, "TaskName cannot be null"); byte[] fanOutBytes = fanOutStore.get(toFanOutStoreKey(taskName)); if (ArrayUtils.isEmpty(fanOutBytes)) { return ImmutableMap.of(); } StartpointFanOutPerTask startpointFanOutPerTask = objectMapper.readValue(fanOutBytes, StartpointFanOutPerTask.class); return ImmutableMap.copyOf(startpointFanOutPerTask.getFanOuts()); }
Source:
<code>private void close(final boolean clean) { <START> if (clean && checkpointNeeded) { <END> executeAndMaybeSwallow(true, this::writeCheckpointIfNeed, "state manager checkpoint", log); } switch (state()) { case CREATED: case RUNNING: case RESTORING: case SUSPENDED: executeAndMaybeSwallow( clean, () -> StateManagerUtil.closeStateManager( log, logPrefix, clean, eosEnabled, stateMgr, stateDirectory, TaskType.ACTIVE ), "state manager close", log); executeAndMaybeSwallow(clean, recordCollector::close, "record collector close", log); break; case CLOSED: log.trace("Skip closing since state is {}", state()); return; default: throw new IllegalStateException("Unknown state " + state() + " while closing active task " + id); } partitionGroup.close(); closeTaskSensor.record(); transitionTo(State.CLOSED); }</code><technical_language>A if (clean) sufficient</technical_language>

Target:
private void close(final boolean clean) { if (clean) { executeAndMaybeSwallow(true, this::writeCheckpointIfNeed, "state manager checkpoint", log); } switch (state()) { case CREATED: case RUNNING: case RESTORING: case SUSPENDED: executeAndMaybeSwallow( clean, () -> StateManagerUtil.closeStateManager( log, logPrefix, clean, eosEnabled, stateMgr, stateDirectory, TaskType.ACTIVE ), "state manager close", log); executeAndMaybeSwallow(clean, recordCollector::close, "record collector close", log); break; case CLOSED: log.trace("Skip closing since state is {}", state()); return; default: throw new IllegalStateException("Unknown state " + state() + " while closing active task " + id); } partitionGroup.close(); closeTaskSensor.record(); transitionTo(State.CLOSED); }