auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void exportFilesAsList() throws SemanticException, IOException { if (dataPathList.isEmpty()) { <START> return; <END> } boolean done = false; int repeat = 0; while (!done) { try (BufferedWriter writer = writer()) { for (Path dataPath : dataPathList) { writeFilesList(listFilesInDir(dataPath), writer, AcidUtils.getAcidSubDir(dataPath)); } done = true; } catch (IOException e) { repeat++; logger.info("writeFilesList failed with exception : " + e.getMessage() + " for " + repeat + " time"); if (repeat >= MAX_IO_ERROR_RETRY) { logger.error("exporting data files in dir : " + dataPathList + " to " + exportRootDataDir + " failed"); throw e; } try { logger.info(" sleep for 100 milliseconds before retry " + (repeat)); Thread.sleep(100); } catch (InterruptedException timerEx) { logger.info("thread sleep interrupted", timerEx.getMessage()); } dataFileSystem = dataPathList.get(0).getFileSystem(hiveConf); exportFileSystem = exportRootDataDir.getFileSystem(hiveConf); exportFileSystem.deleteOnExit(new Path(exportRootDataDir, EximUtil.FILES_NAME)); } } }</code><technical_language>if dataPathList is empty, need create empty file. I think, REPL LOAD expect it. base code does</technical_language>

Target:
private void exportFilesAsList() throws SemanticException, IOException, LoginException { if (dataPathList.isEmpty()) { return; } boolean done = false; int repeat = 0; while (!done) { try (BufferedWriter writer = writer()) { for (Path dataPath : dataPathList) { writeFilesList(listFilesInDir(dataPath), writer, AcidUtils.getAcidSubDir(dataPath)); } done = true; } catch (IOException e) { repeat++; logger.info("writeFilesList failed", e); if (repeat >= FileUtils.MAX_IO_ERROR_RETRY) { logger.error("exporting data files in dir : " + dataPathList + " to " + exportRootDataDir + " failed"); throw e; } int sleepTime = FileUtils.getSleepTime(repeat - 1); logger.info(" sleep for milliseconds for retry num ", sleepTime , repeat); try { Thread.sleep(sleepTime); } catch (InterruptedException timerEx) { logger.info("thread sleep interrupted", timerEx.getMessage()); } FileSystem.closeAllForUGI(Utils.getUGI()); dataFileSystem = dataPathList.get(0).getFileSystem(hiveConf); exportFileSystem = exportRootDataDir.getFileSystem(hiveConf); Path exportPath = new Path(exportRootDataDir, EximUtil.FILES_NAME); if (exportFileSystem.exists(exportPath)) { exportFileSystem.delete(exportPath, true); } } } }
Source:
<code>public void testCmdEnvironment() throws Exception { CommandLineExecutorService cles = Framework.getLocalService(CommandLineExecutorService.class); assertNotNull(cles); <START> <END> deployContrib("org.nuxeo.ecm.platform.commandline.executor", "OSGI-INF/commandline-env-test-contrib.xml"); applyInlineDeployments(); List<String> cmds = cles.getRegistredCommands(); assertNotNull(cmds); assertTrue(cmds.contains("echo")); ExecResult result = cles.execCommand("echo", cles.getDefaultCmdParameters()); assertTrue(result.isSuccessful()); assertSame(0, result.getReturnCode()); assertTrue( String.format("Output should contain %s:\n%s", Environment.getDefault().getTemp().getPath(), result.getOutput()), String.join("", result.getOutput()).contains(Environment.getDefault().getTemp().getPath())); }</code><technical_language>pushInlineDeployments</technical_language>

Target:
public void testCmdEnvironment() throws Exception { CommandLineExecutorService cles = Framework.getLocalService(CommandLineExecutorService.class); assertNotNull(cles); pushInlineDeployments("org.nuxeo.ecm.platform.commandline.executor:OSGI-INF/commandline-env-test-contrib.xml"); List<String> cmds = cles.getRegistredCommands(); assertNotNull(cmds); assertTrue(cmds.contains("echo")); ExecResult result = cles.execCommand("echo", cles.getDefaultCmdParameters()); assertTrue(result.isSuccessful()); assertSame(0, result.getReturnCode()); assertTrue( String.format("Output should contain %s:\n%s", Environment.getDefault().getTemp().getPath(), result.getOutput()), String.join("", result.getOutput()).contains(Environment.getDefault().getTemp().getPath())); }
Source:
<code>public StructuredRecord getCurrentValue(StructuredRecord.Builder recordBuilder) throws IOException, InterruptedException { <START> return recordTransformer.transform(delegate.getCurrentKey().datum()); <END> }</code><technical_language>point of passing in recordBuilder is for here. builder path field set, is supposed setup correct output schema. it, output wrong record. add a new method AvroToStructuredTransformer lets pass in a GenericRecord, Schema, StructuredRecord.Builder, a field skip</technical_language>

Target:
public StructuredRecord getCurrentValue(StructuredRecord.Builder recordBuilder) throws IOException, InterruptedException { AvroJob.setOutputKeySchema(job, new org.apache.avro.Schema.Parser().parse(schema.toString())); StructuredRecord ret = recordTransformer.transform(recordBuilder, delegate.getCurrentKey().datum(), schema, pathField); return ret; }
Source:
<code>public MediaServerConfiguration load(String filepath) throws Exception { MediaServerConfiguration configuration = new MediaServerConfiguration(); XMLConfiguration xml; try { try { xml = this.configurations.xml(filepath); } catch (ConfigurationException e) { log.warn("Could not load configuration from " + filepath); final String mmsHome = System.getProperty(MMS_HOME); filepath = mmsHome + DEFAULT_PATH; xml = this.configurations.xml(filepath); log.warn("Configuration file found at " + filepath); } configureNetwork(xml.configurationAt("network"), configuration.getNetworkConfiguration()); configureController(xml.configurationAt("controller"), configuration.getControllerConfiguration()); configureMedia(xml.configurationAt("media"), configuration.getMediaConfiguration()); configureResource(xml.configurationAt("resources"), configuration.getResourcesConfiguration()); configureDtls(xml.configurationAt("dtls"), configuration.getDtlsConfiguration()); <START> } catch (Exception e) { <END> log.error("Could not load configuration from " + filepath + ". Reason: " + e.getMessage()); throw e; } return configuration; }</code><technical_language>Remove catch, need re-throw exception catching in upper layer</technical_language>

Target:
public MediaServerConfiguration load(String filepath) throws Exception { MediaServerConfiguration configuration = new MediaServerConfiguration(); XMLConfiguration xml; try { xml = this.configurations.xml(filepath); } catch (ConfigurationException e) { log.warn("Could not load configuration from " + filepath); final String mmsHome = System.getProperty(MMS_HOME); filepath = mmsHome + DEFAULT_PATH; xml = this.configurations.xml(filepath); log.warn("Configuration file found at " + filepath); } configureNetwork(xml.configurationAt("network"), configuration.getNetworkConfiguration()); configureController(xml.configurationAt("controller"), configuration.getControllerConfiguration()); configureMedia(xml.configurationAt("media"), configuration.getMediaConfiguration()); configureResource(xml.configurationAt("resources"), configuration.getResourcesConfiguration()); configureDtls(xml.configurationAt("dtls"), configuration.getDtlsConfiguration()); return configuration; }
Source:
<code><START> public String failed() throws IOException { <END> final Object result = this.client.call( LuaCommand.FAILED.toString()); return result.toString(); }</code><technical_language>This returns a Map<String, Long> of failure groups number of jobs in failure group: <LINK_0> <LINK_1></technical_language>

Target:
public Map<String, Long> failed() throws IOException { final Object result = this.client.call( LuaCommand.FAILED.toString()); final JavaType javaType = new ObjectMapper().getTypeFactory().constructMapType( HashMap.class, String.class, Long.class); return JsonUtils.parse(result.toString(), javaType); }
Source:
<code>public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { <START> throw new FilterNotCreatedException(e.getMessage()); <END> } }</code><technical_language>pass e, message</technical_language>

Target:
public Filter createFilter(FilterFactoryParams params) throws FilterNotCreatedException { try { return createFilter(parseCategories(params.getArgs())); } catch (ClassNotFoundException e) { throw new FilterNotCreatedException(e); } }
Source:
<code><START> private void maybeCloseNetworkChannel(boolean forceClose) { <END> lastWriteFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); }</code><technical_language>forceClose method</technical_language>

Target:
private boolean maybeCloseNetworkChannel(boolean forceClose) { lastWriteFuture.addListener(ChannelFutureListener.CLOSE); logger.trace("Requested closing of channel {}", ctx.channel()); return true; }
Source:
<code>private void ingestFileObjectAsWork(ContentContainerObject parent, Resource parentResc, Resource childResc) throws DepositException { if (skipResumed(childResc)) { return; } PID childPid = PIDs.get(childResc.getURI()); PID workPid = repository.mintContentPid(); Model workModel = ModelFactory.createDefaultModel(); String label = getPropertyValue(childResc, CdrDeposit.label); if (label == null) { label = getPropertyValue(childResc, CdrDeposit.stagingLocation); if (label == null) { throw new DepositException("No staging location provided for file object (" + childResc.getURI() + ")"); } label = new File(label).getName(); } Resource workResc = workModel.createResource(workPid.getRepositoryPath()); workResc.addProperty(DC.title, label); FedoraTransaction tx = repository.startTransaction(); try { <START> WorkObject newWork = repository.createWorkObject(workPid, workModel); <END> addFileToWork(newWork, childResc); newWork.setPrimaryObject(childPid); parent.addMember(newWork); addClicks(1); log.info("Created work for file object for deposit {}", new Object[] {workPid, childPid, getDepositPID()}); } finally { tx.close(); } }</code><technical_language>Need indent rest of contents of this block</technical_language>

Target:
private void ingestFileObjectAsWork(ContentContainerObject parent, Resource parentResc, Resource childResc) throws DepositException { if (skipResumed(childResc)) { return; } PID childPid = PIDs.get(childResc.getURI()); PID workPid = repository.mintContentPid(); Model workModel = ModelFactory.createDefaultModel(); String label = getPropertyValue(childResc, CdrDeposit.label); if (label == null) { label = getPropertyValue(childResc, CdrDeposit.stagingLocation); if (label == null) { throw new DepositException("No staging location provided for file object (" + childResc.getURI() + ")"); } label = new File(label).getName(); } Resource workResc = workModel.createResource(workPid.getRepositoryPath()); workResc.addProperty(DC.title, label); FedoraTransaction tx = repository.startTransaction(); try { WorkObject newWork = repository.createWorkObject(workPid, workModel); addFileToWork(newWork, childResc); newWork.setPrimaryObject(childPid); parent.addMember(newWork); addClicks(1); log.info("Created work for file object for deposit {}", new Object[] {workPid, childPid, getDepositPID()}); } catch(Exception e) { tx.cancel(e); } finally { tx.close(); } }
Source:
<code>public static List<String> explode(final String input) { List<String> result = newArrayList(); if (isNull(input)) { return result; } char[] characters = input.toCharArray(); for (int i = 0; i < input.length(); i++) { <START> result.add(String.valueOf(characters[i])); <END> } return result; }</code><technical_language>foreach operator</technical_language>

Target:
public static List<String> explode(final String input) { List<String> result = newArrayList(); if (isNull(input)) { return result; } for (char character : input.toCharArray()) { result.add(String.valueOf(character)); } return result; }
Source:
<code>public RoomMediator getFirstRoomMediator(ClientMediatorPod pod) { Log.log(Level.FINEST, pod, "getFirstRoomMediator: builder={0}, new={1}", Log.getHexHash(this), pod.room == null); boolean newbie = pod.room == null; Site site = mapClient.getSite(Constants.FIRST_ROOM); if ( site == null ) { site = FirstRoom.getFallbackSite(); } <START> String playerMode = "full"; <END> String targetId = null; SignedJWT clientJwt = pod.getParsedClientJwt(); if(clientJwt!=null) { Claims c = clientJwt.getClaims(); if(c.containsKey("playerMode")) { playerMode = c.get("playerMode", String.class); targetId = c.get("story", String.class); } } if("guided".equals(playerMode)) { return new GuidedFirstRoom(nexus.getMultiUserView(Constants.FIRST_ROOM), pod.getEncodedServerJwt(), playerClient, mapClient, site, targetId); } else { return new FirstRoom(nexus.getMultiUserView(Constants.FIRST_ROOM), pod.getEncodedServerJwt(), playerClient, mapClient, site, newbie); } }</code><technical_language>"default"</technical_language>

Target:
public RoomMediator getFirstRoomMediator(ClientMediatorPod pod) { Log.log(Level.FINEST, pod, "getFirstRoomMediator: builder={0}, new={1}", Log.getHexHash(this), pod.room == null); boolean newbie = pod.room == null; Site site = mapClient.getSite(Constants.FIRST_ROOM); if ( site == null ) { site = FirstRoom.getFallbackSite(); } String playerMode = "default"; String targetId = null; SignedJWT clientJwt = pod.getParsedClientJwt(); if(clientJwt!=null) { Claims c = clientJwt.getClaims(); if(c.containsKey("playerMode")) { playerMode = c.get("playerMode", String.class); targetId = c.get("story", String.class); } } if("guided".equals(playerMode)) { return new GuidedFirstRoom(nexus.getMultiUserView(Constants.FIRST_ROOM), pod.getEncodedServerJwt(), playerClient, mapClient, site, targetId); } else { return new FirstRoom(nexus.getMultiUserView(Constants.FIRST_ROOM), pod.getEncodedServerJwt(), playerClient, mapClient, site, newbie); } }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { log.debug("Entered AuthorizeServlet QueryString: {}, Parameters : {}", request.getQueryString(), SsoUtils.getRequestParameters(request)); String responseType = SsoUtils.getRequestParameter(request, SsoConstants.JSON_RESPONSE_TYPE); if (!responseType.equals("code")) { throw new OAuthException(SsoConstants.ERR_CODE_INVALID_REQUEST, String.format( ssoContext.getLocalizationUtils().localize( SsoConstants.APP_ERROR_UNSUPPORTED_PARAMETER_IN_REQUEST, (Locale) request.getAttribute(SsoConstants.LOCALE)), responseType, SsoConstants.JSON_RESPONSE_TYPE)); } login(request, response, buildSsoSession(request)); } catch (Exception ex) { SsoSession ssoSession = SsoUtils.getSsoSession(request, true); if (ssoSession.isOpenIdScope() || <START> SsoUtils.scopeAsList(SsoUtils.getScopeRequestParameter(request, "")).contains(SsoConstants.OPENID_SCOPE)) { <END> ssoSession.setRedirectUri(request.getParameter(SsoConstants.HTTP_PARAM_REDIRECT_URI)); } SsoUtils.redirectToErrorPage(request, response, ex); } }</code><technical_language>Line exceeds 120 chars</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { log.debug("Entered AuthorizeServlet QueryString: {}, Parameters : {}", request.getQueryString(), SsoUtils.getRequestParameters(request)); String responseType = SsoUtils.getRequestParameter(request, SsoConstants.JSON_RESPONSE_TYPE); if (!responseType.equals("code")) { throw new OAuthException(SsoConstants.ERR_CODE_INVALID_REQUEST, String.format( ssoContext.getLocalizationUtils().localize( SsoConstants.APP_ERROR_UNSUPPORTED_PARAMETER_IN_REQUEST, (Locale) request.getAttribute(SsoConstants.LOCALE)), responseType, SsoConstants.JSON_RESPONSE_TYPE)); } login(request, response, buildSsoSession(request)); } catch (Exception ex) { SsoSession ssoSession = SsoUtils.getSsoSession(request, true); String scope = SsoUtils.getScopeRequestParameter(request, ""); if (ssoSession.isOpenIdScope() || SsoUtils.scopeAsList(scope).contains(SsoConstants.OPENID_SCOPE)) { ssoSession.setRedirectUri(request.getParameter(SsoConstants.HTTP_PARAM_REDIRECT_URI)); } SsoUtils.redirectToErrorPage(request, response, ex); } }
Source:
<code>public void copyObject(String bucketName, String objectName, String destBucketName, String destObjectName, CopyConditions copyConditions, Map<String,String> metadata) throws InvalidKeyException, InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, IOException, XmlPullParserException, InvalidArgumentException { if (bucketName == null) { throw new InvalidArgumentException("Source bucket name cannot be empty"); } if (objectName == null) { throw new InvalidArgumentException("Source object name cannot be empty"); } if (destBucketName == null) { throw new InvalidArgumentException("Destination bucket name cannot be empty"); } String sourceObjectPath = S3Escaper.encodePath(bucketName + "/" + objectName); if (destObjectName == null) { destObjectName = objectName; } Map<String, String> headerMap = new HashMap<>(); headerMap.put("x-amz-copy-source", sourceObjectPath); if (copyConditions != null) { headerMap.putAll(copyConditions.getConditions()); } if (metadata != null) { <START> headerMap.putAll(Collections.unmodifiableMap(metadata)); <END> } HttpResponse response = executePut(destBucketName, destObjectName, headerMap, null, "", 0); CopyObjectResult result = new CopyObjectResult(); result.parseXml(response.body().charStream()); response.body().close(); }</code><technical_language>headerMap.putAll() adds keys/values metadata. This operation do modification metadata. Unable understand wrapping metadata Collections.unmodifiableMap wrapping. I missing something</technical_language>

Target:
public void copyObject(String bucketName, String objectName, String destBucketName, String destObjectName, CopyConditions copyConditions, Map<String,String> metadata) throws InvalidKeyException, InvalidBucketNameException, NoSuchAlgorithmException, InsufficientDataException, NoResponseException, ErrorResponseException, InternalException, IOException, XmlPullParserException, InvalidArgumentException { if (bucketName == null) { throw new InvalidArgumentException("Source bucket name cannot be empty"); } if (objectName == null) { throw new InvalidArgumentException("Source object name cannot be empty"); } if (destBucketName == null) { throw new InvalidArgumentException("Destination bucket name cannot be empty"); } String sourceObjectPath = S3Escaper.encodePath(bucketName + "/" + objectName); if (destObjectName == null) { destObjectName = objectName; } Map<String, String> headerMap = new HashMap<>(); headerMap.put("x-amz-copy-source", sourceObjectPath); if (copyConditions != null) { headerMap.putAll(copyConditions.getConditions()); } if (metadata != null) { headerMap.putAll(metadata); } HttpResponse response = executePut(destBucketName, destObjectName, headerMap, null, "", 0); CopyObjectResult result = new CopyObjectResult(); result.parseXml(response.body().charStream()); response.body().close(); }
Source:
<code>protected void run() <START> throws UnloggedFailure, Failure, Exception { <END> stdout.println("Hello, cookbook administrator"); }</code><technical_language>needed, missed in previous review</technical_language>

Target:
protected void run() { stdout.println("Hello, cookbook administrator"); }
Source:
<code>public List<ObjectId> revListAll() throws GitException { List<ObjectId> oidList = new ArrayList<>(); RevListCommand revListCommand = revList_(); revListCommand.all(); revListCommand.to(oidList); try { revListCommand.execute(); } catch (InterruptedException e) { throw new GitException(e); <START> } catch (IOException e) { <END> throw new GitException(e); } return oidList; }</code><technical_language>NIT: multi-catch - (surely move parent 1.625 if is already?)</technical_language>

Target:
public List<ObjectId> revListAll() throws GitException { List<ObjectId> oidList = new ArrayList<>(); RevListCommand revListCommand = revList_(); revListCommand.all(); revListCommand.to(oidList); try { revListCommand.execute(); } catch (InterruptedException | IOException e) { throw new GitException(e); } return oidList; }
Source:
<code>protected void buildAuditMessage(StringBuilder builder) { super.buildAuditMessage(builder); SortedSet<String> roleSet = new TreeSet<>(); roleSet.addAll(users.keySet()); roleSet.addAll(groups.keySet()); roleSet.addAll(roles.keySet()); builder.append(", Roles("); List<String> lines = new LinkedList<>(); List<String> tmpLines = null; for (String role : roleSet) { tmpLines = new LinkedList<>(); lines.add(role + ": ["); if (users.get(role) != null && !users.get(role).isEmpty()) { tmpLines.add(" Users: " + StringUtils.join(users.get(role), ", ")); } if (groups.get(role) != null && !groups.get(role).isEmpty()) { tmpLines.add(" Groups: " + StringUtils.join(groups.get(role), ", ")); } if (roles.get(role) != null && !roles.get(role).isEmpty()) { tmpLines.add(" Roles: " + StringUtils.join(roles.get(role), ", ")); } lines.add(StringUtils.join(tmpLines, ";")); lines.add("] "); } <START> builder.append(StringUtils.join(lines, "")); <END> builder.append(")"); }</code><technical_language>is separator lines, line appended builder in loop, lines is longer needed. tmpLines renamed lines. applies ViewPrivilegeChangeRequestAuditEvent.java</technical_language>

Target:
protected void buildAuditMessage(StringBuilder builder) { super.buildAuditMessage(builder); SortedSet<String> roleSet = new TreeSet<>(); roleSet.addAll(users.keySet()); roleSet.addAll(groups.keySet()); roleSet.addAll(roles.keySet()); builder.append(", Roles("); List<String> lines = new LinkedList<>(); for (String role : roleSet) { List<String> tmpLines = new LinkedList<>(); lines.add(role + ": ["); if (users.get(role) != null && !users.get(role).isEmpty()) { tmpLines.add("Users: " + StringUtils.join(users.get(role), ", ")); } if (groups.get(role) != null && !groups.get(role).isEmpty()) { tmpLines.add("Groups: " + StringUtils.join(groups.get(role), ", ")); } if (roles.get(role) != null && !roles.get(role).isEmpty()) { tmpLines.add("Roles: " + StringUtils.join(roles.get(role), ", ")); } lines.add(StringUtils.join(tmpLines, ";")); lines.add("] "); } builder.append(StringUtils.join(lines, "")); builder.append(")"); }
Source:
<code>public void setAttribute(String attributeName, Object attributeValue) { if (attributeValue == null) { this.delta.put(attributeName, DeltaValue.REMOVED); } else { final Object existingAttributeValue = this.delegate.getAttribute(attributeName); if (existingAttributeValue != null) { <START> if (existingAttributeValue == attributeValue && ClassUtils.isPrimitiveOrWrapper(attributeValue.getClass())) { <END> this.delta.put(attributeName, DeltaValue.UPDATED); } } else { this.delta.put(attributeName, DeltaValue.ADDED); } } this.delegate.setAttribute(attributeName, attributeValue); if (PRINCIPAL_NAME_INDEX_NAME.equals(attributeName) || SPRING_SECURITY_CONTEXT.equals(attributeName)) { this.changed = true; } }</code><technical_language>implementation correct glance. handled existingAttributeValue != attributeValue update well. if (existingAttributeValue != attributeValue) { this.delta.put(attributeName, DeltaValue.UPDATED); }else if(!ClassUtils.isPrimitiveOrWrapper(attributeValue.getClass() || !attributeValue.getClass().equals(String.class))){ this.delta.put(attributeName, DeltaValue.UPDATED); }</technical_language>

Target:
public void setAttribute(String attributeName, Object attributeValue) { final Object existingAttributeValue = this.delegate.getAttribute(attributeName); boolean attributeExists = (existingAttributeValue != null); boolean attributeRemoved = (attributeValue == null); if (!attributeExists && attributeRemoved) { return; } if (attributeExists) { if (attributeRemoved) { this.delta.merge(attributeName, DeltaValue.REMOVED, (oldDeltaValue, deltaValue) -> oldDeltaValue == DeltaValue.ADDED ? null : deltaValue); } else if (existingAttributeValue.getClass() != attributeValue.getClass() || !isImmutable(existingAttributeValue.getClass()) || !attributeValue.equals(existingAttributeValue)) { this.delta.merge(attributeName, DeltaValue.UPDATED, (oldDeltaValue, deltaValue) -> oldDeltaValue == DeltaValue.ADDED ? oldDeltaValue : deltaValue); } } else { this.delta.merge(attributeName, DeltaValue.ADDED, (oldDeltaValue, deltaValue) -> oldDeltaValue == DeltaValue.ADDED ? oldDeltaValue : DeltaValue.UPDATED); } this.delegate.setAttribute(attributeName, attributeValue); if (PRINCIPAL_NAME_INDEX_NAME.equals(attributeName) || SPRING_SECURITY_CONTEXT.equals(attributeName)) { this.changed = true; } }
Source:
<code>private void addToDuplicateLibs(Map<String, Set<Dependency>> map, Dependency dependency) { String coordinate = getCoordinate(dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), null); if (!map.containsKey(coordinate)) { Set<Dependency> set = new HashSet<>(); map.put(coordinate, set); } boolean exist = false; <START> for (Dependency dep : map.get(coordinate)) { <END> if (dep.getGroupId().equals(dependency.getGroupId()) && dep.getArtifactId().equals(dependency.getArtifactId()) && dep.getVersion().equals(dependency.getVersion()) && dep.getType().equals(dependency.getType())) { exist = true; break; } } if (!exist) { map.get(coordinate).add(dependency); } }</code><technical_language>overwrite hasCode equals of SortableDependeny is ok, need compare</technical_language>

Target:
private void addToDuplicateLibs(Map<String, Set<Dependency>> map, Dependency dependency) { String coordinate = getCoordinate(dependency.getGroupId(), dependency.getArtifactId(), dependency.getType(), null); if (!map.containsKey(coordinate)) { Set<Dependency> set = new HashSet<>(); map.put(coordinate, set); } map.get(coordinate).add(dependency); }
Source:
<code>private void checkPlainText() { if (expectedLines == null) { expectedLines = headerFormat.split("(?:\r)?\n|\r"); } CompatibleInputFile inputFile = getContext().getFile(); List<String> lines; <START> try (InputStreamReader inr = new InputStreamReader(inputFile.inputStream(), inputFile.charset())) { <END> lines = CharStreams.readLines(inr); } catch (IOException e) { throw new IllegalStateException("Unable to execute rule \"S1451\" for file " + getContext().getFileName(), e); } if (!matches(expectedLines, lines)) { addIssue(new FileIssue(this, MESSAGE)); } }</code><technical_language>avoid libs for this. new BufferedReader(new InputStreamReader(stream, charset)).lines().collect(...)</technical_language>

Target:
private void checkPlainText() { if (expectedLines == null) { expectedLines = headerFormat.split("(?:\r)?\n|\r"); } JavaScriptFile file = getContext().getJavaScriptFile(); List<String> lines = CheckUtils.readLines(file); if (!matches(expectedLines, lines)) { addIssue(new FileIssue(this, MESSAGE)); } }
Source:
<code>public void shutdown(final boolean clean) { <START> log.debug("Shutting down all active tasks in" + "\n" + <END> "Created: {}" + "\n" + "Restoring: {}" + "\n" + "Running: {}" + "\n" + "Suspended: {}", created.keySet(), restoring.keySet(), running.keySet(), suspended.keySet()); super.shutdown(clean); }</code><technical_language>nit: in mode" + add clean boolean?. Ditto otherwise</technical_language>

Target:
public void shutdown(final boolean clean) { final String shutdownType = clean ? "Clean" : "Unclean"; log.debug(shutdownType + " shutdown of all active tasks" + "\n" + "non-initialized tasks to close: {}" + "\n" + "restoring tasks to close: {}" + "\n" + "running tasks to close: {}" + "\n" + "suspended tasks to close: {}", clean, created.keySet(), restoring.keySet(), running.keySet(), suspended.keySet()); super.shutdown(clean); }
Source:
<code>public static void withContextIfNeed(UUID secSubjId, GridKernalContext ctx, RunnableX r) throws IgniteCheckedException { IgniteSecurity security = ctx.security(); try { if (security.enabled() && secSubjId != null) { try (OperationSecurityContext s = security.withContext(secSubjId)) { r.runx(); } } else r.runx(); } catch (Exception e) { if (e instanceof IgniteCheckedException) throw (IgniteCheckedException)e; <START> throw new IgniteCheckedException(e); <END> } }</code><technical_language>do need change exception here? throw it</technical_language>

Target:
public static void withContextIfNeed(UUID secSubjId, GridKernalContext ctx, RunnableX r) { IgniteSecurity security = ctx.security(); if (security.enabled() && secSubjId != null) { try (OperationSecurityContext s = security.withContext(secSubjId)) { r.run(); } } else r.run(); }
Source:
<code>public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); final Runnable task = new Runnable() { @Override public void run() { <START> handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), <END> (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } }; scheduler.schedule(task, gatewayArtifactSynchronizerProperties.getEventWaitingTime(), TimeUnit.MILLISECONDS); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } } catch (JMSException e) { log.error("JMSException occurred when processing the received message ", e); } }</code><technical_language>I putting this event handled in a thread. started a delay. start a task API is need deployed</technical_language>

Target:
public void onMessage(Message message) { try { if (message != null) { if (log.isDebugEnabled()) { log.debug("Event received in JMS Event Receiver - " + message); } Topic jmsDestination = (Topic) message.getJMSDestination(); if (message instanceof MapMessage) { MapMessage mapMessage = (MapMessage) message; Map<String, Object> map = new HashMap<String, Object>(); Enumeration enumeration = mapMessage.getMapNames(); while (enumeration.hasMoreElements()) { String key = (String) enumeration.nextElement(); map.put(key, mapMessage.getObject(key)); } if (APIConstants.TopicNames.TOPIC_NOTIFICATION.equalsIgnoreCase(jmsDestination.getTopicName())) { if (map.get(APIConstants.EVENT_TYPE) != null) { if (debugEnabled) { log.debug("Event received from the topic of " + jmsDestination.getTopicName()); } handleNotificationMessage((String) map.get(APIConstants.EVENT_TYPE), (Long) map.get(APIConstants.EVENT_TIMESTAMP), (String) map.get(APIConstants.EVENT_PAYLOAD)); } } } else { log.warn("Event dropped due to unsupported message type " + message.getClass()); } } else { log.warn("Dropping the empty/null event received through jms receiver"); } } catch (JMSException e) { log.error("JMSException occurred when processing the received message ", e); } }
Source:
<code>public double getCommandedSteeringAngle() { int closestIndex = getClosestIndex(wayPoints,pose); if(closestIndex == -1){ return 17433504; } double delta = 10; int targetIndex = closestIndex; while(GPSPoseMessage.getDistance(pose,wayPoints.get(targetIndex).toGpsPoseMessage(0)) < delta){ targetIndex = targetIndex+1; } if(targetIndex >= wayPoints.size()) { return 0; } GpsMeasurement targetPoint = wayPoints.get(targetIndex); double dx = targetPoint.getLongitude() - pose.getLongitude(); <START> double dy = targetPoint.getLatitude() - pose.getLatitude(); <END> double desiredHeading = 180*Math.atan2(dy, dx)/Math.PI; return desiredHeading - pose.getHeading(); }</code><technical_language>here, name this dLon dLat</technical_language>

Target:
public double getCommandedSteeringAngle() { int closestIndex = getClosestIndex(wayPoints,pose); if(closestIndex == -1){ return 17433504; } double delta = 10; int targetIndex = closestIndex; while(GPSPoseMessage.getDistance(pose,wayPoints.get(targetIndex).toGpsPoseMessage(0)) < delta){ targetIndex = targetIndex+1; } if(targetIndex >= wayPoints.size()) { return 0; } GpsMeasurement targetPoint = wayPoints.get(targetIndex); double dLon = targetPoint.getLongitude() - pose.getLongitude(); double dLat = targetPoint.getLatitude() - pose.getLatitude(); double desiredHeading = 180*Math.atan2(dLat, dLon)/Math.PI; return desiredHeading - pose.getHeading(); }
Source:
<code>private void addAPIs(List<ComponentManifest.API> apis, String appContextPath, String componentContextPath, String componentName, ClassLoader classLoader) { if ((apis == null) || apis.isEmpty()) { return; } for (ComponentManifest.API api : apis) { String className = api.getClassName(); String uri = appContextPath + componentContextPath + "/apis" + api.getUri(); Object apiImplementation; try { apiImplementation = classLoader.loadClass(className).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { <START> throw new UUFException("Error in deploying API " + className, e); <END> } Dictionary<String, String> serviceProperties = new Hashtable<>(); serviceProperties.put("contextPath", uri); classLoaderProvider.deployAPI(apiImplementation, serviceProperties); LOGGER.info("Deployed API '{}' in component '{}' with the context path '{}'.", className, componentName, uri); } }</code><technical_language>change exception message "Cannot deploy REST API {className} for component {componentName}"</technical_language>

Target:
private void addAPIs(List<ComponentManifest.API> apis, String appContextPath, String componentContextPath, String componentName, ClassLoader classLoader) { if ((apis == null) || apis.isEmpty()) { return; } for (ComponentManifest.API api : apis) { String className = api.getClassName(); String uri = appContextPath + componentContextPath + "/apis" + api.getUri(); Object apiImplementation; try { apiImplementation = classLoader.loadClass(className).newInstance(); } catch (InstantiationException | IllegalAccessException | ClassNotFoundException e) { throw new UUFException("Cannot deploy REST API '" + className + "' for component '" + componentName + "'", e); } Dictionary<String, String> serviceProperties = new Hashtable<>(); serviceProperties.put("contextPath", uri); classLoaderProvider.deployAPI(apiImplementation, serviceProperties); LOGGER.info("Deployed REST API '{}' for component '{}' with context path '{}'.", className, componentName, uri); } }
Source:
<code>protected Cluster buildGroup(GroupParams<Node.NodeParams> groupParams) { <START> if (groupParams.getType().equals(CorfuServerParams.class)) { <END> groupParams.getNodesParams().forEach(node -> FAKE_DNS.addForwardResolution(node.getName(), InetAddress.getLoopbackAddress()) ); return DockerCorfuCluster.builder() .universeParams(universeParams) .params(ClassUtils.cast(groupParams)) .loggingParams(loggingParams) .docker(docker) .build(); }if (groupParams.getType().equals(SupportServerParams.class)) { groupParams.getNodesParams().forEach(node -> FAKE_DNS.addForwardResolution(node.getName(), InetAddress.getLoopbackAddress()) ); return DockerSupportCluster.builder() .universeParams(universeParams) .monitoringParams(ClassUtils.cast(groupParams)) .loggingParams(loggingParams) .docker(docker) .build(); } else { throw new UniverseException("Unknown node type"); } }</code><technical_language>decide getNodeType</technical_language>

Target:
protected Cluster buildGroup(GroupParams<Node.NodeParams> groupParams) { switch (groupParams.getType()) { case CORFU_CLUSTER: groupParams.getNodesParams().forEach(node -> FAKE_DNS.addForwardResolution(node.getName(), InetAddress.getLoopbackAddress()) ); return DockerCorfuCluster.builder() .universeParams(universeParams) .params(ClassUtils.cast(groupParams)) .loggingParams(loggingParams) .docker(docker) .build(); case SUPPORT_CLUSTER: groupParams.getNodesParams().forEach(node -> FAKE_DNS.addForwardResolution(node.getName(), InetAddress.getLoopbackAddress()) ); return DockerSupportCluster.builder() .universeParams(universeParams) .monitoringParams(ClassUtils.cast(groupParams)) .loggingParams(loggingParams) .docker(docker) .build(); default: throw new UniverseException("Unknown node type"); } }
Source:
<code>public void testSafelyHandleModuleInfo() throws IOException { <START> ZipFile zipFile = new ZipFile(libraryModuleInfoJar.toFile()); <END> ZipEntry entry = zipFile.getEntry("module-info.class"); ClassCache cache = new ClassCache( ImmutableSet.of(), ImmutableSet.of(), ImmutableSet.of(), ImmutableSet.of(), false); try (InputStream classStream = zipFile.getInputStream(entry)) { ClassReader reader = new ClassReader(classStream); DepsCheckerClassVisitor checker = new DepsCheckerClassVisitor(cache, null); reader.accept(checker, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } }</code><technical_language>please enclose zipFile a try-with-resources well, similar classStream</technical_language>

Target:
public void testSafelyHandleModuleInfo() throws IOException { try (ZipFile zipFile = new ZipFile(libraryModuleInfoJar.toFile())) { ZipEntry entry = zipFile.getEntry("module-info.class"); ClassCache cache = new ClassCache( ImmutableSet.of(), ImmutableSet.of(), ImmutableSet.of(), ImmutableSet.of(), false); try (InputStream classStream = zipFile.getInputStream(entry)) { ClassReader reader = new ClassReader(classStream); DepsCheckerClassVisitor checker = new DepsCheckerClassVisitor(cache, null); reader.accept(checker, ClassReader.SKIP_DEBUG | ClassReader.SKIP_FRAMES); } } }
Source:
<code>private static TenantId tenantOf(Iterable<Command> commands) { <START> Iterator<Command> iterator = commands.iterator(); <END> if (!iterator.hasNext()) { return TenantId.getDefaultInstance(); } TenantId result = iterator.next().tenant(); return result; }</code><technical_language>kind of more concise (via a Stream, Iterator)</technical_language>

Target:
private static TenantId tenantOf(Iterable<Command> commands) { Iterator<Command> iterator = commands.iterator(); return iterator.hasNext() ? iterator.next().tenant() : TenantId.getDefaultInstance(); }
Source:
<code>public void higherTrustLevelWins() throws MalformedURLException, IOException, FetcherException { final URL lowUrl = new URL("<LINK_0>"); final URL highUrl = new URL("<LINK_1>"); FulltextFetcher finderHigh = mock(FulltextFetcher.class); FulltextFetcher finderLow = mock(FulltextFetcher.class); when(finderHigh.getTrustLevel()).thenReturn(TrustLevel.SOURCE); when(finderLow.getTrustLevel()).thenReturn(TrustLevel.UNKNOWN); when(finderHigh.findFullText(entry)).thenReturn(Optional.of(highUrl)); when(finderLow.findFullText(entry)).thenReturn(Optional.of(lowUrl)); <START> FulltextFetchers fetcher = new FulltextFetchers(new HashSet<>(Arrays.asList(finderLow, finderHigh))); <END> assertEquals(Optional.of(highUrl), fetcher.findFullTextPDF(entry)); }</code><technical_language>This feels ugly. another constructor added FullTextFetchers caller need pass a sortedset, more easy? Maybe, ... fetcherLow fetcherHigh passed</technical_language>

Target:
public void higherTrustLevelWins() throws MalformedURLException, IOException, FetcherException { final URL lowUrl = new URL("<LINK_0>"); final URL highUrl = new URL("<LINK_1>"); FulltextFetcher finderHigh = mock(FulltextFetcher.class); FulltextFetcher finderLow = mock(FulltextFetcher.class); when(finderHigh.getTrustLevel()).thenReturn(TrustLevel.SOURCE); when(finderLow.getTrustLevel()).thenReturn(TrustLevel.UNKNOWN); when(finderHigh.findFullText(entry)).thenReturn(Optional.of(highUrl)); when(finderLow.findFullText(entry)).thenReturn(Optional.of(lowUrl)); FulltextFetchers fetcher = new FulltextFetchers(Set.of(finderLow, finderHigh)); assertEquals(Optional.of(highUrl), fetcher.findFullTextPDF(entry)); }
Source:
<code>public List<Block> filter(Block block) { if (VALID_PLAINTEXT_BLOCKS.contains(block.getClass())) { return Collections.singletonList(block); } if (LinkBlock.class.isAssignableFrom(block.getClass()) && block.getChildren().isEmpty()) { ResourceReference reference = ((LinkBlock) block).getReference(); try { String label; ResourceType resourceType = reference.getType(); boolean cond = ResourceType.DOCUMENT.equals(resourceType) || ResourceType.SPACE.equals(resourceType); <START> label = cond ? this.linkLabelGenerator.generate(reference) : reference.getReference(); <END> return this.plainTextParser.parse(new StringReader(label)).getChildren().get(0).getChildren(); } catch (ParseException e) { throw new RuntimeException("Failed to parse link label as plain text", e); } } return Collections.emptyList(); }</code><technical_language>I find this a lot readable version</technical_language>

Target:
public List<Block> filter(Block block) { if (VALID_PLAINTEXT_BLOCKS.contains(block.getClass())) { return Collections.singletonList(block); } if (LinkBlock.class.isAssignableFrom(block.getClass()) && block.getChildren().isEmpty()) { ResourceReference reference = ((LinkBlock) block).getReference(); return filterLinkBlock(reference); } return Collections.emptyList(); }
Source:
<code>public synchronized Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments) { requireNonNull(insertHandle, "insertHandle is null"); <START> checkArgument(insertHandle instanceof MemoryInsertTableHandle); <END> MemoryInsertTableHandle memoryInsertHandle = (MemoryInsertTableHandle) insertHandle; updateRowsOnHosts(memoryInsertHandle.getTable(), fragments); return Optional.empty(); }</code><technical_language>Remove instanceof checks - add value. other implementations of ConnectorMetadata</technical_language>

Target:
public synchronized Optional<ConnectorOutputMetadata> finishInsert(ConnectorSession session, ConnectorInsertTableHandle insertHandle, Collection<Slice> fragments) { requireNonNull(insertHandle, "insertHandle is null"); MemoryInsertTableHandle memoryInsertHandle = (MemoryInsertTableHandle) insertHandle; updateRowsOnHosts(memoryInsertHandle.getTable(), fragments); return Optional.empty(); }
Source:
<code>private String asString(Object value) { if ( value instanceof String ) { return ( String ) value; } Integer i = (Integer) value; if ( i == 0 ) <START> return ""; <END> else return enumValues[((Integer) value) - 1]; }</code><technical_language>this necessary</technical_language>

Target:
private String asString(Object value) { if ( value instanceof String ) { return ( String ) value; } Integer i = (Integer) value; if ( i == 0 ) return null; else return enumValues[((Integer) value) - 1]; }
Source:
<code>public void setup() { <START> Link link = new Link(new Shell(), SWT.NONE); <END> event = new HyperlinkEvent(link, "uri://test", "link", 0); linkEventConsumer = new HyperlinkEventConsumer(); }</code><technical_language>shell disposed in teardown</technical_language>

Target:
public void setup() { event = new HyperlinkEvent(link, "uri://test", "link", 0); linkEventConsumer = new HyperlinkEventConsumer(); }
Source:
<code>public void run() { if (logger.isDebugEnabled()) { logger.debug("Read selector running for connections to " + this.getHost() + ":" + this.getPort()); } try { this.selector = Selector.open(); while (this.isActive()) { SocketChannel newChannel; int soTimeout = this.getSoTimeout(); int selectionCount = 0; try { selectionCount = selector.select(soTimeout < 0 ? 0 : soTimeout); } catch (CancelledKeyException cke) { if (logger.isDebugEnabled()) { logger.debug("CancelledKeyException during Selector.select()"); } } catch (ClosedSelectorException cse) { throw cse; <START> } <END> while ((newChannel = newChannels.poll()) != null) { try { newChannel.register(this.selector, SelectionKey.OP_READ, channelMap.get(newChannel)); } catch (ClosedChannelException cce) { if (logger.isDebugEnabled()) { logger.debug("Channel closed before registering with selector for reading"); } } catch (ClosedSelectorException cse) { throw cse; } } this.processNioSelections(selectionCount, selector, null, this.channelMap); } } catch (ClosedSelectorException cse) { if (this.isActive()) { logger.error("Selector closed", cse); } } catch (Exception e) { logger.error("Exception in read selector thread", e); this.setActive(false); } if (logger.isDebugEnabled()) { logger.debug("Read selector exiting for connections to " + this.getHost() + ":" + this.getPort()); } }</code><technical_language>Redundant catch ClosedSelectorException here. rethrow catch more time in wrapping block</technical_language>

Target:
public void run() { if (logger.isDebugEnabled()) { logger.debug("Read selector running for connections to " + this.getHost() + ":" + this.getPort()); } try { this.selector = Selector.open(); while (this.isActive()) { SocketChannel newChannel; int soTimeout = this.getSoTimeout(); int selectionCount = 0; try { selectionCount = selector.select(soTimeout < 0 ? 0 : soTimeout); } catch (CancelledKeyException cke) { if (logger.isDebugEnabled()) { logger.debug("CancelledKeyException during Selector.select()"); } } while ((newChannel = newChannels.poll()) != null) { try { newChannel.register(this.selector, SelectionKey.OP_READ, channelMap.get(newChannel)); } catch (ClosedChannelException cce) { if (logger.isDebugEnabled()) { logger.debug("Channel closed before registering with selector for reading"); } } } this.processNioSelections(selectionCount, selector, null, this.channelMap); } } catch (ClosedSelectorException cse) { if (this.isActive()) { logger.error("Selector closed", cse); } } catch (Exception e) { logger.error("Exception in read selector thread", e); this.setActive(false); } if (logger.isDebugEnabled()) { logger.debug("Read selector exiting for connections to " + this.getHost() + ":" + this.getPort()); } }
Source:
<code>public void addPossibleSinkForValue(String value, HttpMessage sink) { synchronized (possibleSinksForValues) { List<HttpMessage> sinkList; sinkList = possibleSinksForValues.get(value); if (sinkList == null) { sinkList = new ArrayList<HttpMessage>(); possibleSinksForValues.put(value, sinkList); } <START> for (HttpMessage s : sinkList) { if (s.equals(sink)) { return; } } <END> sinkList.add(sink); } }</code><technical_language>faced issue of duplicate sinks ? For i scans duplicate sinks, I is resetting SinkStorage session ? I this is remove them, LinkedHashSet HashSet for same. WDYT</technical_language>

Target:
public void addPossibleSinkForValue(String value, HttpMessage sink) { synchronized (possibleSinksForValues) { Set<Integer> sinksForValue = possibleSinksForValues.get(value); if (sinksForValue == null) { sinksForValue = new HashSet<>(); possibleSinksForValues.put(value, sinksForValue); } boolean newMessage = sinksForValue.add(sink.hashCode()); if (newMessage) { int msgId = messagesStorage.storeMessage(sink); messagesHashToStorageIds.put(sink.hashCode(), msgId); } } }
Source:
<code>public final RpcOptions build() { <START> return new RpcOptions(timeout, TimeUnit.MILLISECONDS, responseFilter, responseMode, skipReplicationQueue, fifoOrder, <END> totalOrder); }</code><technical_language>I need unit here</technical_language>

Target:
public final RpcOptions build() { return new RpcOptions(timeout, unit, responseFilter, responseMode, skipReplicationQueue, fifoOrder, totalOrder); }
Source:
<code>protected void testIntersections(Comparison comparison) { assertFalse(Iterables.any(comparison.getDifferences(), new Predicate<Diff>() { @SuppressWarnings("restriction") public boolean apply(Diff input) { return Iterators.size(Iterators .filter(input.getRefines().iterator(), <START> not(instanceOf(MultiplicityReferenceChange.class)))) <END> > 1; } })); }</code><technical_language>is purpose of testIntersections(Comparison)? weird need filter MultiplicityReferenceChanges of other numerous UMLDiff extensions. filter interested in instead</technical_language>

Target:
protected void testIntersections(Comparison comparison) { assertFalse(Iterables.any(comparison.getDifferences(), new Predicate<Diff>() { public boolean apply(Diff input) { return input.getRefines().size() > 1; } })); }