auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static void prepareResourcesToInject(Props props, String workingDir) { try { Configuration conf = new Configuration(false); loadProp(props, conf, "azkaban.link.execution.url"); loadProp(props, conf, "azkaban.link.workflow.url"); loadProp(props, conf, "azkaban.link.job.url"); loadProp(props, conf, "azkaban.link.jobexec.url"); loadProp(props, conf, "azkaban.link.attempt.url"); loadProp(props, conf, "azkaban.job.outnodes"); loadProp(props, conf, "azkaban.job.innodes"); addHadoopProperties(props); <START> Map<String, String> confProperties = props.getMapByPrefix(injectPrefix); <END> for (Map.Entry<String, String> entry : confProperties.entrySet()) { String confKey = entry.getKey().replace(injectPrefix, ""); String confVal = entry.getValue(); conf.set(confKey, confVal); } File file = getConfFile(props, workingDir, injectFile); OutputStream xmlOut = new FileOutputStream(file); conf.writeXml(xmlOut); xmlOut.close(); } catch (Throwable e) { _logger.error("Encountered error while preparing the Hadoop configuration resource file", e); } }</code><technical_language>Please rename injectPrefix INJECT_PREFIX injectFile INJECT_FILE</technical_language>

Target:
public static void prepareResourcesToInject(Props props, String workingDir) { try { Configuration conf = new Configuration(false); addHadoopProperties(props); Map<String, String> confProperties = props.getMapByPrefix(INJECT_PREFIX); for (Map.Entry<String, String> entry : confProperties.entrySet()) { String confKey = entry.getKey().replace(INJECT_PREFIX, ""); String confVal = entry.getValue(); conf.set(confKey, confVal); } File file = getConfFile(props, workingDir, INJECT_FILE); OutputStream xmlOut = new FileOutputStream(file); conf.writeXml(xmlOut); xmlOut.close(); } catch (Throwable e) { _logger.error("Encountered error while preparing the Hadoop configuration resource file", e); } }
Source:
<code>public void close() throws IOException { if (this.iterator instanceof Closeable) { ((Closeable) this.iterator).close(); } if (!this.root.equals(this.iterator)) { <START> if (this.root instanceof Closeable) { <END> ((Closeable) this.root).close(); } } }</code><technical_language>Gary, opposite: public interface Closeable extends AutoCloseable {</technical_language>

Target:
public void close() { if (this.iterator instanceof AutoCloseable) { try { ((AutoCloseable) this.iterator).close(); } catch (Exception e) { } } if (this.closeable != null) { try { this.closeable.close(); } catch (Exception e) { } } }
Source:
<code>public void testRecordWithLogicalTypes() throws IOException { TestRecordWithLogicalTypes record = new TestRecordWithLogicalTypes(true, 34, 35L, 3.14F, 3019.34, null, <START> LocalDate.now(), LocalTime.now(), ZonedDateTime.now().with(DateTimeZone.UTC), <END> new BigDecimal(123.45f).setScale(2, RoundingMode.HALF_DOWN)); File data = write(TestRecordWithLogicalTypes.getClassSchema(), record); List<TestRecordWithLogicalTypes> actual = read(TestRecordWithLogicalTypes.getClassSchema(), data); Assert.assertEquals("Should match written record", record, actual.get(0)); }</code><technical_language>some imports missing here</technical_language>

Target:
public void testRecordWithLogicalTypes() throws IOException { TestRecordWithLogicalTypes record = new TestRecordWithLogicalTypes(true, 34, 35L, 3.14F, 3019.34, null, LocalDate.now(), LocalTime.now(), Instant.now(), new BigDecimal(123.45f).setScale(2, RoundingMode.HALF_DOWN)); File data = write(TestRecordWithLogicalTypes.getClassSchema(), record); List<TestRecordWithLogicalTypes> actual = read(TestRecordWithLogicalTypes.getClassSchema(), data); Assert.assertEquals("Should match written record", record, actual.get(0)); }
Source:
<code>private void processNextResponse() throws ClientProtocolError, ClientConnectionException { int resSize = readInt(); if (resSize <= 0) throw new ClientProtocolError(String.format("Invalid response size: %s", resSize)); long bytesReadOnStartReq = totalBytesRead; long resId = readLong(); ClientRequestFuture pendingReq = pendingReqs.get(resId); if (pendingReq == null) throw new ClientProtocolError(String.format("Unexpected response ID [%s]", resId)); int status = 0; BinaryInputStream resIn; status = readInt(); <START> int hdrSize = (int)(totalBytesRead - bytesReadOnStartReq); <END> if (status == 0) { if (resSize <= hdrSize) pendingReq.onDone(); else pendingReq.onDone(read(resSize - hdrSize)); } else { resIn = new BinaryHeapInputStream(read(resSize - hdrSize)); String err = new BinaryReaderExImpl(null, resIn, null, true).readString(); switch (status) { case ClientStatus.SECURITY_VIOLATION: pendingReq.onDone(new ClientAuthorizationException()); default: pendingReq.onDone(new ClientServerError(err, status, resId)); } } }</code><technical_language>approach counting totalBytesRead fragile counting methods everywhere. I counting a header size encapsulated a method object counting bytes while reading header only</technical_language>

Target:
private void processNextResponse() throws ClientProtocolError, ClientConnectionException { int resSize = readInt(); if (resSize <= 0) throw new ClientProtocolError(String.format("Invalid response size: %s", resSize)); long bytesReadOnStartReq = totalBytesRead; long resId = readLong(); ClientRequestFuture pendingReq = pendingReqs.get(resId); if (pendingReq == null) throw new ClientProtocolError(String.format("Unexpected response ID [%s]", resId)); int status; BinaryInputStream resIn; status = readInt(); int hdrSize = (int)(totalBytesRead - bytesReadOnStartReq); if (status == 0) { if (resSize <= hdrSize) pendingReq.onDone(); else pendingReq.onDone(read(resSize - hdrSize)); } else { resIn = new BinaryHeapInputStream(read(resSize - hdrSize)); String err = new BinaryReaderExImpl(null, resIn, null, true).readString(); switch (status) { case ClientStatus.SECURITY_VIOLATION: pendingReq.onDone(new ClientAuthorizationException()); default: pendingReq.onDone(new ClientServerError(err, status, resId)); } } }
Source:
<code>private void createFolder(Path folder) throws IOException { if (Files.notExists(folder)) { try { Files.createDirectory(folder); } catch (IOException e) { <START> throw new IOException("Error during creation of repository structure.", e); <END> } } }</code><technical_language>this superflous? Files.createDirectory directlry throw excption</technical_language>

Target:
private void createFolder(Path folder) throws IOException { if (Files.notExists(folder)) { Files.createDirectory(folder); } }
Source:
<code>public FeatureVector[] classify(Object[] examples) { if (!(examples instanceof Word[])) { <START> String type = examples == null ? "null" : examples.getClass().getName(); <END> logger.error("Classifier 'Affixes(Word)' defined on line 107 of CommonFeatures.lbj received '" + type + "' as input."); new Exception().printStackTrace(); System.exit(1); } return super.classify(examples); }</code><technical_language>exit(), print STDERR</technical_language>

Target:
public FeatureVector[] classify(Object[] examples) { if (!(examples instanceof Word[])) { String type = examples == null ? "null" : examples.getClass().getName(); System.err.println("Classifier 'Affixes(Word)' defined on line 107 of CommonFeatures.lbj received '" + type + "' as input."); new Exception().printStackTrace(); System.exit(1); } return super.classify(examples); }
Source:
<code><START> private void addClassificationsToBuildReport(Run<?, ?> build, FilePath workspace, TaskListener listener, Configuration configuration, List<Classification> listToAdd) throws InterruptedException, IOException { <END> if (CollectionUtils.isNotEmpty(listToAdd)) { for (Classification classification : listToAdd) { log(listener, String.format("Adding classification - %s:%s", classification.key, classification.value)); configuration.addClassifications(classification.key, evaluateMacro(build, workspace, listener, classification.value)); } } }</code><technical_language>listToAdd is null earlier..</technical_language>

Target:
private void addClassificationsToBuildReport(Run<?, ?> build, FilePath workspace, TaskListener listener, Configuration configuration, List<Classification> listToAdd) throws InterruptedException, IOException { for (Classification classification : listToAdd) { log(listener, String.format("Adding classification - %s:%s", classification.key, classification.value)); configuration.addClassifications(classification.key, evaluateMacro(build, workspace, listener, classification.value)); } }
Source:
<code>private boolean hasHeader(List<String> contents) { boolean headerValid = true; boolean statusFound = false; boolean typeFound = false; if (!hasHeaderSeparatorInContent(contents)) { return false; } <START> if (!headerSeparatorDemarcatesHeader(contents)) { <END> return false; } for (String line : contents) { if (hasHeaderSeparator(line)) { LOGGER.debug("Header separator found"); break; } if (isTypeProperty(line)) { LOGGER.debug("Type property found"); typeFound = true; } if (isStatusProperty(line)) { LOGGER.debug("Status property found"); statusFound = true; } if (!line.isEmpty() && !line.contains("=")) { LOGGER.error("Property found without assignment [{}]", line); headerValid = false; } } return headerValid && (statusFound || hasDefaultStatus()) && (typeFound || hasDefaultType()); }</code><technical_language>I this check obsoletes previous hasHeaderSeparatorInContent(). For a quick fix this solution is good</technical_language>

Target:
private boolean hasHeader(List<String> contents) { boolean headerValid = true; boolean statusFound = false; boolean typeFound = false; if (!headerSeparatorDemarcatesHeader(contents)) { return false; } for (String line : contents) { if (hasHeaderSeparator(line)) { LOGGER.debug("Header separator found"); break; } if (isTypeProperty(line)) { LOGGER.debug("Type property found"); typeFound = true; } if (isStatusProperty(line)) { LOGGER.debug("Status property found"); statusFound = true; } if (!line.isEmpty() && !line.contains("=")) { LOGGER.error("Property found without assignment [{}]", line); headerValid = false; } } return headerValid && (statusFound || hasDefaultStatus()) && (typeFound || hasDefaultType()); }
Source:
<code>private void addQuotaModeTypes(VersionCaps version) { <START> if (VersionUtils.greaterOrEqual(version, VERSION_3_2)) { <END> version.setQuotaModeTypes(new QuotaModeTypes()); for (QuotaModeType mode : QuotaModeType.values()) { version.getQuotaModeTypes().getQuotaModeTypes().add(mode.value()); } } }</code><technical_language>This 3.6, if "quota mode" concept sinnce 3.2</technical_language>

Target:
private void addQuotaModeTypes(VersionCaps version) { if (VersionUtils.greaterOrEqual(version, VERSION_3_6)) { version.setQuotaModeTypes(new QuotaModeTypes()); for (QuotaModeType mode : QuotaModeType.values()) { version.getQuotaModeTypes().getQuotaModeTypes().add(mode.value()); } } }
Source:
<code>public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } <START> for (String key : expressionMap.keySet()) { <END> if (key != null && pattern.matches(key)) { Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); return expression; } } return null; }</code><technical_language>add final</technical_language>

Target:
public Expression lookup(final String pattern) { if (expressionMap.containsKey(pattern)) { return expressionMap.get(pattern); } for (final String key : expressionMap.keySet()) { if (key != null && pattern.matches(key)) { final Expression expression = expressionMap.get(key); expressionMap.put(pattern, expression); return expression; } } return null; }
Source:
<code>private void readMySQLCharset() { readIf(EQUAL); <START> readIf("UTF8"); readIf("UTF8MB4"); readIf("UTF8MB4_BIN"); <END> }</code><technical_language>Java if (!readIf("UTF8") && !readIf("UTF8MB4")) { read("UTF8MB4_BIN"); } it</technical_language>

Target:
private void readMySQLCharset() { readIf(EQUAL); readUniqueIdentifier(); }
Source:
<code>public WebResourceResponse shouldInterceptRequest(WebView view, String url) { WebResourceResponse response = null; response =super.shouldInterceptRequest(view, url); if (response == null) { Uri origUri = Uri.parse(url); if (origUri.getHost().equals("localhost")) { CordovaResourceApi resourceApi = cordovaWebView.getResourceApi(); Uri remappedUri = Uri.parse("file:/ OpenForReadResult result; try { <START> result = resourceApi.openForRead(remappedUri, true); <END> response = new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream); } catch (IOException e) { response = new WebResourceResponse("text/plain", "UTF-8", null); } } } return response; }</code><technical_language>this API barf if pass straight relative URL. Test cases for Cordova assert relative paths /foo file:///android_asset/www/../foo this leaves open interpretation. public OpenForReadResult openForRead(Uri uri) throws IOException \* @throws Throws InvalidArgumentException for relative URIs. Relative URIs \* resolved passed this function</technical_language>

Target:
public WebResourceResponse shouldInterceptRequest(WebView view, String url) { WebResourceResponse response = super.shouldInterceptRequest(view, url); if (response != null) { return response; } Uri origUri = Uri.parse(url); if (!origUri.getHost().equals("localhost")) { return null; } try { String localPath = WWW_DIR + origUri.getPath(); if (!isFileUnder(localPath, WWW_DIR)) { throw new IOException("Trying to access file outside assets/www"); } else { Uri localUri = Uri.parse("file://" + localPath); CordovaResourceApi resourceApi = cordovaWebView.getResourceApi(); OpenForReadResult result = resourceApi.openForRead(localUri, true); Log.i("SalesforceIceCreamWebViewClient.shouldInterceptRequest", "Loading local file:" + localUri); return new WebResourceResponse(result.mimeType, "UTF-8", result.inputStream); } } catch (IOException e) { Log.e("SalesforceIceCreamWebViewClient.shouldInterceptRequest", "Invalid localhost url:" + url, e); return new WebResourceResponse("text/plain", "UTF-8", null); } }
Source:
<code>public static File[] getJarFilesFromPattern(File dir, String pattern) { final Pattern jarPattern = Pattern.compile(pattern); File[] foundJarFiles = dir.listFiles(new FileFilter() { @Override public boolean accept(File f) { return jarPattern.matcher(f.getName()).matches(); } }); if (foundJarFiles == null) { foundJarFiles = new File[0]; } else if (foundJarFiles.length > 1) { <START> throw new RuntimeException(foundJarFiles.length + " files found looking for " + pattern); <END> } return foundJarFiles; }</code><technical_language>mention directory in exception too</technical_language>

Target:
public static File[] getJarFilesFromPattern(File dir, String pattern) { Pattern jarPattern = Pattern.compile(pattern); File[] foundJarFiles = dir.listFiles(f -> jarPattern.matcher(f.getName()).matches()); if (foundJarFiles == null) { foundJarFiles = new File[0]; } else if (foundJarFiles.length > 1) { throw new RuntimeException(foundJarFiles.length + " files found in " + dir.getAbsolutePath() + " looking for " + pattern); } return foundJarFiles; }
Source:
<code>public void testSetChatUser() throws Exception { Player player = PlayerBuilder.create("junit") .defaultValues() .clan("e") <START> .avatar(new AvatarBean(new URL("<LINK_1>"), "dog")) <END> .get(); instance.setChatUser(ChatChannelUserBuilder.create("junit").defaultValues().setPlayer(player).get()); WaitForAsyncUtils.waitForFxEvents(); assertThat(instance.clanMenu.getText(), is("[e]")); assertThat(instance.clanMenu.isVisible(), is(true)); verify(countryFlagService).loadCountryFlag("US"); assertThat(instance.countryTooltip, CoreMatchers.notNullValue()); assertThat(instance.avatarTooltip, CoreMatchers.notNullValue()); assertThat(instance.userTooltip, CoreMatchers.notNullValue()); verify(clanTooltipControllerMock).setClan(testClan); }</code><technical_language>stay neutral <LINK_0></technical_language>

Target:
public void testSetChatUser() throws Exception { Player player = PlayerBuilder.create("junit") .defaultValues() .clan("e") .avatar(new AvatarBean(new URL("<LINK_0>"), "dog")) .get(); instance.setChatUser(ChatChannelUserBuilder.create("junit").defaultValues().setPlayer(player).get()); WaitForAsyncUtils.waitForFxEvents(); assertThat(instance.clanMenu.getText(), is("[e]")); assertThat(instance.clanMenu.isVisible(), is(true)); verify(countryFlagService).loadCountryFlag("US"); assertThat(instance.countryTooltip, CoreMatchers.notNullValue()); assertThat(instance.avatarTooltip, CoreMatchers.notNullValue()); assertThat(instance.userTooltip, CoreMatchers.notNullValue()); verify(clanTooltipControllerMock).setClan(testClan); }
Source:
<code>public IDescriptionPreprocessor caseViewExtensionDescription(ViewExtensionDescription object) { <START> Collection<EStructuralFeature> featuresToIgnore = Lists.newArrayList(); <END> Collection<EStructuralFeature> featuresToCopy = Lists.newArrayList(); featuresToCopy.add(PropertiesPackage.Literals.VIEW_EXTENSION_DESCRIPTION__METAMODELS); return new DefaultDescriptionPreprocessorWithFiltering<ViewExtensionDescription>(ViewExtensionDescription.class, featuresToIgnore, featuresToCopy); }</code><technical_language>remove, new ArrayList<>() in constructor, lines</technical_language>

Target:
public Optional<IDescriptionPreprocessor> caseViewExtensionDescription(ViewExtensionDescription object) { Collection<EStructuralFeature> featuresToCopy = new ArrayList<>(); featuresToCopy.add(PropertiesPackage.Literals.VIEW_EXTENSION_DESCRIPTION__METAMODELS); return Optional.of(new DefaultDescriptionPreprocessorWithFiltering<ViewExtensionDescription>(ViewExtensionDescription.class, new ArrayList<>(), featuresToCopy)); }
Source:
<code>public ToolNBT buildTagData(List<Material> materials) { <START> return buildDefaultTag(materials); <END> }</code><technical_language>needs proper building math bonus durability for a big tool</technical_language>

Target:
public ToolNBT buildTagData(List<Material> materials) { HandleMaterialStats handle = materials.get(0).getStatsOrUnknown(MaterialTypes.HANDLE); HeadMaterialStats head = materials.get(1).getStatsOrUnknown(MaterialTypes.HEAD); HandleMaterialStats handle2 = materials.get(2).getStatsOrUnknown(MaterialTypes.HANDLE); ExtraMaterialStats extra = materials.get(3).getStatsOrUnknown(MaterialTypes.EXTRA); ToolNBT data = new ToolNBT(); data.head(head); data.handle(handle, handle2); data.extra(extra); data.harvestLevel = head.harvestLevel; data.durability *= DURABILITY_MODIFIER; return data; }
Source:
<code>public static void listJobTemplates(String projectId, String location) throws IOException { try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) { var listJobTemplatesRequest = ListJobTemplatesRequest.newBuilder() .setParent(LocationName.of(projectId, location).toString()) .build(); TranscoderServiceClient.ListJobTemplatesPagedResponse response = transcoderServiceClient.listJobTemplates(listJobTemplatesRequest); System.out.println("Job templates:"); for (JobTemplate jt : response.iterateAll()) { <START> System.out.println(jt); <END> } } }</code><technical_language>nit: do want print out entire payload name</technical_language>

Target:
public static void listJobTemplates(String projectId, String location) throws IOException { try (TranscoderServiceClient transcoderServiceClient = TranscoderServiceClient.create()) { var listJobTemplatesRequest = ListJobTemplatesRequest.newBuilder() .setParent(LocationName.of(projectId, location).toString()) .build(); TranscoderServiceClient.ListJobTemplatesPagedResponse response = transcoderServiceClient.listJobTemplates(listJobTemplatesRequest); System.out.println("Job templates:"); for (JobTemplate jobTemplate : response.iterateAll()) { System.out.println(jobTemplate.getName()); } } }
Source:
<code>public String extract(HttpServletRequest request) throws RemoteUserExtractionException { <START> if (request.getParameter(doAsParam) != null && enableDoAs) { <END> String doAsUser = paramRemoteUserExtractor.extract(request); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(request.getRemoteUser()); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(doAsUser, ugi); try { ProxyUsers.authorize(proxyUser, request.getRemoteAddr()); return doAsUser; } catch (AuthorizationException e) { throw new RemoteUserExtractionException(e.getMessage()); } } else { return requestRemoteUserExtractor.extract(request); } }</code><technical_language>This simplified remove enableDoAs logic</technical_language>

Target:
public String extract(HttpServletRequest request) throws RemoteUserExtractionException { if (request.getParameter(userExtractParam) != null) { String extractedUser = paramRemoteUserExtractor.extract(request); UserGroupInformation ugi = UserGroupInformation.createRemoteUser(request.getRemoteUser()); UserGroupInformation proxyUser = UserGroupInformation.createProxyUser(extractedUser, ugi); try { ProxyUsers.authorize(proxyUser, request.getRemoteAddr()); return extractedUser; } catch (AuthorizationException e) { throw new RemoteUserExtractionException(e.getMessage(), e); } } else { LOG.warn("The parameter used to extract user doesn't exist in the request."); return requestRemoteUserExtractor.extract(request); } }
Source:
<code>protected static String readPipe(File dir, String[] command, String encoding) { <START> final boolean debug = SystemReader.getInstance().getProperty( <END> "jgit.fs.debug") != null; try { if (debug) System.out.println("readpipe " + Arrays.asList(command) + "," + dir); final Process p = Runtime.getRuntime().exec(command, null, dir); final BufferedReader lineRead = new BufferedReader( new InputStreamReader(p.getInputStream(), encoding)); p.getOutputStream().close(); Thread gobbler = new Thread() { public void run() { InputStream is = p.getErrorStream(); try { int ch; if (debug) while ((ch = is.read()) != -1) System.err.print((char) ch); else while (is.read() != -1) { } } catch (IOException e) { e.printStackTrace(System.err); } try { is.close(); } catch (IOException e) { e.printStackTrace(System.err); } } }; gobbler.start(); String r = null; try { r = lineRead.readLine(); if (debug) System.err.println("readpipe returned '" + r + "'"); String l; while ((l = lineRead.readLine()) != null) { if (debug) System.err.println(l); } } finally { p.getErrorStream().close(); lineRead.close(); } for (;;) { try { int rc = p.waitFor(); if (rc == 0 && r != null && r.length() > 0) return r; if (debug) System.err.println("readpipe rc=" + rc); break; } catch (InterruptedException ie) { } } } catch (IOException e) { if (debug) System.err.println(e); } return null; }</code><technical_language>Do need this debugging code in? If I prefer Boolean parse variable support true/false set/unset</technical_language>

Target:
protected static String readPipe(File dir, String[] command, String encoding) { final boolean debug = Boolean.parseBoolean(SystemReader.getInstance() .getProperty("jgit.fs.debug")); try { if (debug) System.out.println("readpipe " + Arrays.asList(command) + "," + dir); final Process p = Runtime.getRuntime().exec(command, null, dir); final BufferedReader lineRead = new BufferedReader( new InputStreamReader(p.getInputStream(), encoding)); p.getOutputStream().close(); final AtomicBoolean gooblerFail = new AtomicBoolean(false); Thread gobbler = new Thread() { public void run() { InputStream is = p.getErrorStream(); try { int ch; if (debug) while ((ch = is.read()) != -1) System.err.print((char) ch); else while (is.read() != -1) { } } catch (IOException e) { e.printStackTrace(System.err); gooblerFail.set(true); } try { is.close(); } catch (IOException e) { e.printStackTrace(System.err); gooblerFail.set(true); } } }; gobbler.start(); String r = null; try { r = lineRead.readLine(); if (debug) { System.err.println("readpipe may return '" + r + "'"); System.err.println("(ignoring remaing output:"); } String l; while ((l = lineRead.readLine()) != null) { if (debug) System.err.println(l); } } finally { p.getErrorStream().close(); lineRead.close(); } for (;;) { try { int rc = p.waitFor(); gobbler.join(); if (rc == 0 && r != null && r.length() > 0 && !gooblerFail.get()) return r; if (debug) System.err.println("readpipe rc=" + rc); break; } catch (InterruptedException ie) { } } } catch (IOException e) { if (debug) System.err.println(e); } if (debug) System.err.println("readpipe returns null"); return null; }
Source:
<code><START> public List<CaptureConfig> onEnableSession() { <END> return new ArrayList<>(); }</code><technical_language>Is a reason this is a list instead of a CaptureConfig? a usage perspective, sense issue a single config</technical_language>

Target:
public CaptureConfig onEnableSession() { return null; }
Source:
<code>private void resolveExternalSymbols() throws SymbolNotFoundException, IllegalAccessSymbolException, DuplicateSymbolException { for( ModuleRecord md : moduleMap.values() ) { <START> for( SymbolInfoExternal localSymbol : md.externalSymbols() ) { <END> if( localSymbol instanceof SymbolWildCard ) { ModuleRecord wildcardImportedRecord = this.moduleMap.get( localSymbol.moduleSource().get().source() ); md.putWildcardImportedRecord( (SymbolWildCard) localSymbol, wildcardImportedRecord.symbols() ); } else { SymbolInfo targetSymbol = symbolSourceLookup( localSymbol ); if( targetSymbol.privacy() == Privacy.PRIVATE ) { throw new IllegalAccessSymbolException( localSymbol.name(), localSymbol.moduleTargets() ); } localSymbol.setPointer( targetSymbol.node() ); } } } }</code><technical_language>Calling external symbol localSymbol is pure evil. :-D</technical_language>

Target:
private void resolveExternalSymbols() throws SymbolNotFoundException, IllegalAccessSymbolException, DuplicateSymbolException { for( ModuleRecord md : moduleMap.values() ) { for( ImportedSymbolInfo externalSymbols : md.symbolTable().externalSymbols() ) { if( externalSymbols instanceof SymbolWildCard ) { ModuleRecord wildcardImportedRecord = this.moduleMap.get( externalSymbols.moduleSource().get().uri() ); md.symbolTable().resolveWildCardSymbol( (SymbolWildCard) externalSymbols, wildcardImportedRecord.symbolTable().symbols() ); } else { SymbolInfo targetSymbol = symbolSourceLookup( externalSymbols ); if( targetSymbol.accessModifier() == AccessModifier.PRIVATE ) { throw new IllegalAccessSymbolException( externalSymbols.name(), externalSymbols.importPath() ); } externalSymbols.resolve( targetSymbol.node() ); } } } }
Source:
<code>protected void process(StateEvent stateEvent, ComplexEventChunk complexEventChunk) { thisStatePreProcessor.stateChanged(); StreamEvent streamEvent = stateEvent.getStreamEvent(stateId); stateEvent.setTimestamp(streamEvent.getTimestamp()); if (nextProcessor != null) { complexEventChunk.reset(); this.isEventReturned = true; } if (nextStatePreProcessor != null) { nextStatePreProcessor.addState(stateEvent); } if (nextEveryStatePreProcessor != null) { if (isGroupedPreprocessor) { <START> nextEveryStatePreProcessor.addEveryState(((StreamPreStateProcessor) nextEveryStatePreProcessor). <END> stateEventPool.borrowEvent()); } else { nextEveryStatePreProcessor.addEveryState(stateEvent); } } if (callbackPreStateProcessor != null) { callbackPreStateProcessor.startStateReset(); } }</code><technical_language>need add state here</technical_language>

Target:
protected void process(StateEvent stateEvent, ComplexEventChunk complexEventChunk) { thisStatePreProcessor.stateChanged(); StreamEvent streamEvent = stateEvent.getStreamEvent(stateId); stateEvent.setTimestamp(streamEvent.getTimestamp()); if (nextProcessor != null) { complexEventChunk.reset(); this.isEventReturned = true; } if (nextStatePreProcessor != null) { nextStatePreProcessor.addState(stateEvent); } if (nextEveryStatePreProcessor != null) { nextEveryStatePreProcessor.addEveryState(stateEvent); } if (callbackPreStateProcessor != null) { callbackPreStateProcessor.startStateReset(); } }
Source:
<code>public ValidationResult isDomainExistAndActive() { <START> if (storageDomain == null) { <END> return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_NOT_EXIST); } if (storageDomain.getStatus() != StorageDomainStatus.Active) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$%1$s %2$s", "status", storageDomain.getStatus().name())); } return ValidationResult.VALID; }</code><technical_language>please replace lines call method added.</technical_language>

Target:
public ValidationResult isDomainExistAndActive() { ValidationResult domainExistValidation = isDomainExist(); if (!ValidationResult.VALID.equals(domainExistValidation)) { return domainExistValidation; } if (storageDomain.getStatus() != StorageDomainStatus.Active) { return new ValidationResult(VdcBllMessages.ACTION_TYPE_FAILED_STORAGE_DOMAIN_STATUS_ILLEGAL2, String.format("$%1$s %2$s", "status", storageDomain.getStatus().name())); } return ValidationResult.VALID; }
Source:
<code>private void publishUpdate(List<String> itemNames, LightwaveRFCommand message, LightwaveRfBindingProvider provider) { <START> logger.info("Publishing Update to {}",message, itemNames); <END> boolean published = false; if (itemNames != null) { for (String itemName : itemNames) { LightwaveRfType deviceType = provider.getTypeForItemName(itemName); State state = message.getState(deviceType); if(state != null){ logger.info("Update from LightwaveRf ItemName[{}], State[{}]", itemName, state); published = true; eventPublisher.postUpdate(itemName, state); } else{ logger.info("State was null for type {}, message {}",itemName, deviceType, message); } } } if (!published) { logger.warn("No item for incoming message[{}]", message.getLightwaveRfCommandString()); } }</code><technical_language>decrease DEBUG level</technical_language>

Target:
private void publishUpdate(List<String> itemNames, LightwaveRFCommand message, LightwaveRfBindingProvider provider) { logger.debug("Publishing Update to {}", message, itemNames); boolean published = false; if (itemNames != null) { for (String itemName : itemNames) { LightwaveRfType deviceType = provider .getTypeForItemName(itemName); State state = message.getState(deviceType); if (state != null) { logger.info( "Update from LightwaveRf ItemName[{}], State[{}]", itemName, state); published = true; eventPublisher.postUpdate(itemName, state); } else { logger.info("State was null for type {}, message {}", itemName, deviceType, message); } } } if (!published) { logger.warn("No item for incoming message[{}]", message.getLightwaveRfCommandString()); } }
Source:
<code>public AuthenticationMechanism create(String mechanismName, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) { <START> String loginPage = properties.get(LOGIN_PAGE); <END> String errorPage = properties.get(ERROR_PAGE); String defaultPage = properties.get(DEFAULT_PAGE); boolean overrideInitial = false; if (properties.containsKey(OVERRIDE_INITIAL)) { overrideInitial = Boolean.parseBoolean(properties.get(OVERRIDE_INITIAL)); } boolean saveOriginal = true; if (properties.containsKey(SAVE_ORIGINAL_REQUEST)) { saveOriginal = Boolean.parseBoolean(properties.get(SAVE_ORIGINAL_REQUEST)); } return new ServletFormAuthenticationMechanism(formParserFactory, mechanismName, loginPage, errorPage, defaultPage, overrideInitial, identityManager, saveOriginal); }</code><technical_language>In this case, I prefer fields final</technical_language>

Target:
public AuthenticationMechanism create(String mechanismName, IdentityManager identityManager, FormParserFactory formParserFactory, Map<String, String> properties) { final String loginPage = properties.get(LOGIN_PAGE); final String errorPage = properties.get(ERROR_PAGE); final String defaultPage = properties.get(DEFAULT_PAGE); final boolean overrideInitial = properties.containsKey(OVERRIDE_INITIAL) ? Boolean.parseBoolean(properties.get(OVERRIDE_INITIAL)): false; boolean saveOriginal = true; if (properties.containsKey(SAVE_ORIGINAL_REQUEST)) { saveOriginal = Boolean.parseBoolean(properties.get(SAVE_ORIGINAL_REQUEST)); } return new ServletFormAuthenticationMechanism(formParserFactory, mechanismName, loginPage, errorPage, defaultPage, overrideInitial, identityManager, saveOriginal); }
Source:
<code><START> public static void setupExtensionConfigs() throws Exception { <END> String configPath = new URI(StartupProperties.get().getProperty("config.store.uri")).getPath(); String location = configPath + "-extensionSore"; StartupProperties.get().setProperty("config.store.uri", location); FileUtils.deleteDirectory(new File(location)); StateStoreProperties.get().setProperty(FalconJPAService.URL, URL); Configuration localConf = new Configuration(); FS.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); FS.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); }</code><technical_language>Nit: public</technical_language>

Target:
public static void setupExtensionConfigs() throws Exception { String configPath = new URI(StartupProperties.get().getProperty("config.store.uri")).getPath(); String location = configPath + "-extensionSore"; StartupProperties.get().setProperty("config.store.uri", location); FileUtils.deleteDirectory(new File(location)); StateStoreProperties.get().setProperty(FalconJPAService.URL, URL); Configuration localConf = new Configuration(); LOCAL_FS.initialize(LocalFileSystem.getDefaultUri(localConf), localConf); LOCAL_FS.mkdirs(new Path(DB_BASE_DIR)); createDB(DB_SQL_FILE); }
Source:
<code>public static Response decrypt(Response response) throws OSException { LOGGER.info("Removes E options from outer options which are not allowed there"); discardEOptions(response); OSCoreCtxDB db = HashMapCtxDB.getInstance(); byte[] protectedData = response.getPayload(); Encrypt0Message enc = null; Token token = response.getToken(); OSCoreCtx ctx = null; OptionSet uOptions = response.getOptions(); if (token != null) { ctx = db.getContextByToken(token); if (ctx == null) { LOGGER.error(ErrorDescriptions.TOKEN_INVALID); throw new OSException(ErrorDescriptions.TOKEN_INVALID); } enc = decompression(protectedData, response); } else { LOGGER.error(ErrorDescriptions.TOKEN_NULL); throw new OSException(ErrorDescriptions.TOKEN_NULL); } <START> byte[] plaintext; <END> try { plaintext = decryptAndDecode(enc, response, ctx, db.getSeqByToken(token)); DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext)); response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS))); response.setOptions(EMPTY); DataParser.parseOptionsAndPayload(reader, response); } catch (Exception e) { LOGGER.error(ErrorDescriptions.DECRYPTION_FAILED); throw new OSException(ErrorDescriptions.DECRYPTION_FAILED); } OptionSet eOptions = response.getOptions(); eOptions = OptionJuggle.merge(eOptions, uOptions); response.setOptions(eOptions); db.removeToken(token); return response; }</code><technical_language>scope of plaintext reduced moving "try"</technical_language>

Target:
public static Response decrypt(Response response) throws OSException { LOGGER.info("Removes E options from outer options which are not allowed there"); discardEOptions(response); OSCoreCtxDB db = HashMapCtxDB.getInstance(); byte[] protectedData = response.getPayload(); Encrypt0Message enc = null; Token token = response.getToken(); OSCoreCtx ctx = null; OptionSet uOptions = response.getOptions(); if (token != null) { ctx = db.getContextByToken(token); if (ctx == null) { LOGGER.error(ErrorDescriptions.TOKEN_INVALID); throw new OSException(ErrorDescriptions.TOKEN_INVALID); } enc = decompression(protectedData, response); } else { LOGGER.error(ErrorDescriptions.TOKEN_NULL); throw new OSException(ErrorDescriptions.TOKEN_NULL); } try { byte[] plaintext = decryptAndDecode(enc, response, ctx, db.getSeqByToken(token)); DatagramReader reader = new DatagramReader(new ByteArrayInputStream(plaintext)); response = OptionJuggle.setRealCodeResponse(response, CoAP.ResponseCode.valueOf(reader.read(CoAP.MessageFormat.CODE_BITS))); response.setOptions(EMPTY); DataParser.parseOptionsAndPayload(reader, response); } catch (Exception e) { LOGGER.error(ErrorDescriptions.DECRYPTION_FAILED); throw new OSException(ErrorDescriptions.DECRYPTION_FAILED); } OptionSet eOptions = response.getOptions(); eOptions = OptionJuggle.merge(eOptions, uOptions); response.setOptions(eOptions); db.removeToken(token); return response; }
Source:
<code>public static DHRobotArm getDHRobotArm() { <START> DHRobotArm arm = new DHRobotArm(); <END> DHLink link1 = new DHLink("omoplate", 0, 40, MathUtils.degToRad(-90), MathUtils.degToRad(-90)); link1.setMin(MathUtils.degToRad(-90)); link1.setMax(MathUtils.degToRad(0)); DHLink link2 = new DHLink("shoulder", -80, 0, MathUtils.degToRad(90), MathUtils.degToRad(90)); link2.setMin(MathUtils.degToRad(-90)); link2.setMax(MathUtils.degToRad(90)); DHLink link3 = new DHLink("rotate", 280, 0, MathUtils.degToRad(0), MathUtils.degToRad(90)); link3.setMin(MathUtils.degToRad(0)); link3.setMax(MathUtils.degToRad(180)); DHLink link4 = new DHLink("bicep", 0, 280, MathUtils.degToRad(90), MathUtils.degToRad(0)); link4.setMin(MathUtils.degToRad(90)); link4.setMax(MathUtils.degToRad(180)); arm.addLink(link1); arm.addLink(link2); arm.addLink(link3); arm.addLink(link4); return arm; }</code><technical_language>Similar, this is specific inmoov arm, a generic body part. this return null log a warning message implemented. (Another approach abstract force a subclass implement it</technical_language>

Target:
public DHRobotArm getDHRobotArm() { if (this.getIntanceName().toLowerCase().contains("arm")) { DHRobotArm arm = new DHRobotArm(); DHLink link1 = new DHLink("omoplate", 0, 40, MathUtils.degToRad(-90), MathUtils.degToRad(-90)); link1.setMin(MathUtils.degToRad(-90)); link1.setMax(MathUtils.degToRad(0)); DHLink link2 = new DHLink("shoulder", -80, 0, MathUtils.degToRad(90), MathUtils.degToRad(90)); link2.setMin(MathUtils.degToRad(-90)); link2.setMax(MathUtils.degToRad(90)); DHLink link3 = new DHLink("rotate", 280, 0, MathUtils.degToRad(0), MathUtils.degToRad(90)); link3.setMin(MathUtils.degToRad(0)); link3.setMax(MathUtils.degToRad(180)); DHLink link4 = new DHLink("bicep", 0, 280, MathUtils.degToRad(90), MathUtils.degToRad(0)); link4.setMin(MathUtils.degToRad(90)); link4.setMax(MathUtils.degToRad(180)); arm.addLink(link1); arm.addLink(link2); arm.addLink(link3); arm.addLink(link4); return arm; } else { log.warn("Kinematics class not yet implemented for this body part"); return null; } }
Source:
<code>public Set<String> getCurrentAssignmentsByResource(String resource) { if (!_currentAssignments.containsKey(resource)) { return Collections.emptySet(); } <START> return _currentAssignments.get(resource); <END> }</code><technical_language>personal preference, for this, I java 8 style getOrDefault a bit cleaner :) java _currentAssignments.getOrDefault(resource, Collections.emptySet());</technical_language>

Target:
public Set<String> getCurrentAssignmentsByResource(String resource) { return _currentAssignments.getOrDefault(resource, Collections.emptySet()); }
Source:
<code>public void testThrowsNotFound() { <START> expectedException.expect(RemoteException.class); <END> expectedException.expectMessage(containsString("Not found")); service.getThrowsNotFound(null); }</code><technical_language>check wrapped error is method throws</technical_language>

Target:
public void testThrowsNotFound() { try { service.getThrowsNotFound(null); fail(); } catch (RemoteException e) { assertThat(e.getMessage(), containsString("Not found")); assertThat(e.getRemoteException().getErrorName(), is("javax.ws.rs.NotFoundException")); } }
Source:
<code>public String source() { <START> return getString("source"); <END> }</code><technical_language>alias getSource() deprecate source()</technical_language>

Target:
public String source() { return getSource(); }
Source:
<code>RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { for (;;) { final RevCommit c = source.next(); if (c == null) return null; boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { <START> if (firstParent && i > 0) { break; } <END> final RevCommit oldp = pList[i]; final RevCommit newp = rewrite(oldp); if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) c.parents = cleanup(pList); return c; } }</code><technical_language>This rewrite drop non-first parents, I think</technical_language>

Target:
RevCommit next() throws MissingObjectException, IncorrectObjectTypeException, IOException { final RevCommit c = source.next(); if (c == null) { return null; } boolean rewrote = false; final RevCommit[] pList = c.parents; final int nParents = pList.length; for (int i = 0; i < nParents; i++) { final RevCommit oldp = pList[i]; if (firstParent && i > 0) { c.parents = new RevCommit[] { rewrite(oldp) }; return c; } final RevCommit newp = rewrite(oldp); if (oldp != newp) { pList[i] = newp; rewrote = true; } } if (rewrote) { c.parents = cleanup(pList); } return c; }
Source:
<code>public void run() { try { Issue result = repo.setMilestone(repoId, issueId, issueTitle, issueMilestone); if (result.getMilestone() == null) { <START> response.complete(issueMilestone == null); <END> } else { response.complete(result.getMilestone().getNumber() == issueMilestone); } } catch (IOException e) { response.completeExceptionally(e); } }</code><technical_language>here. this point checking if input null</technical_language>

Target:
public void run() { Optional<Integer> result; try { result = repo.setMilestone(repoId, issueId, issueTitle, issueMilestone); } catch (IOException e) { response.completeExceptionally(e); return; } response.complete(issueMilestone.equals(result)); }
Source:
<code>public Map<String, String> write() { String name; try { name = ProfileCache.getProfile(uuid).getName(); <START> } catch (NullPointerException e) { <END> name = fallbackName; } Map<String, String> result = new HashMap<>(2); result.put("uuid", uuid.toString()); result.put("name", name); return result; }</code><technical_language>personally letting this kind of exception caught. Handle null correctly this falsely catch</technical_language>

Target:
public Map<String, String> write() { PlayerProfile profile = ProfileCache.getProfile(uuid); String name = profile != null ? profile.getName() : fallbackName; Map<String, String> result = new HashMap<>(2); result.put("uuid", uuid.toString()); result.put("name", name); return result; }
Source:
<code>public JHttpEndpoint(URI uri) { <START> if (StringUtils.startsWith(uri.getPath().toLowerCase(), HTTP.value)) <END> this.protocol = HTTP; else if (StringUtils.startsWith(uri.getPath().toLowerCase(), HTTPS.value)) this.protocol = HTTPS; else throw new IllegalArgumentException(format("Protocol of uri '%s' is unsupported!", uri)); this.hostname = uri.getHost(); this.port = uri.getPort(); }</code><technical_language>switch(uri.getScheme())</technical_language>

Target:
public JHttpEndpoint(URI uri) { try { URL url = uri.toURL(); } catch (MalformedURLException e) { throw new IllegalArgumentException(e); } if (equalsIgnoreCase(uri.getScheme(), HTTP.name())) this.protocol = HTTP; else if (equalsIgnoreCase(uri.getScheme(), HTTPS.name())) this.protocol = HTTPS; else throw new IllegalArgumentException(format("Protocol of uri '%s' is unsupported!", uri)); this.hostname = uri.getHost(); this.port = uri.getPort() < 0 ? 80 : uri.getPort(); }
Source:
<code>public Workflow addService(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Repository path", required = true) @FormParam("repository") String repository, @ApiParam(value = "Name of user on GitHub", required = true) @FormParam("username") String username, @ApiParam(value = "GitHub installation ID", required = true) @FormParam("installationId") String installationId) { String servicePath = "github.com/" + repository; User sendingUser = GitHubHelper.findUserByGitHubUsername(tokenDAO, userDAO, username, true); <START> workflowDAO.findByPath(servicePath, false, Service.class).ifPresent((service) -> { <END> String msg = "A service already exists for GitHub repository " + repository; LOG.info(msg); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); }); String installationAccessToken = GitHubHelper.gitHubAppSetup(gitHubAppId, gitHubPrivateKeyFile, installationId); final GitHubSourceCodeRepo sourceCodeRepo = (GitHubSourceCodeRepo)SourceCodeRepoFactory.createGitHubAppRepo(installationAccessToken); try { sourceCodeRepo.getRepository(repository); } catch (CustomWebApplicationException ex) { String msg = "Repository " + repository + " does not exist on GitHub"; LOG.error(msg); throw new CustomWebApplicationException(msg, LAMBDA_FAILURE); } Service service = sourceCodeRepo.initializeService(repository); service.getUsers().add(sendingUser); long serviceId = workflowDAO.create(service); return workflowDAO.findById(serviceId); }</code><technical_language>Ditto, for Service.class, this for BioWorkflow. generics AbstractWorkflowResource accomplish this</technical_language>

Target:
public Workflow addService(@ApiParam(hidden = true) @Auth User user, @ApiParam(value = "Repository path", required = true) @FormParam("repository") String repository, @ApiParam(value = "Name of user on GitHub", required = true) @FormParam("username") String username, @ApiParam(value = "GitHub installation ID", required = true) @FormParam("installationId") String installationId) { return addEntityFromGitHubRepository(repository, username, installationId); }
Source:
<code>public Map<String, String> getAllMappingUnderPath(String path) throws IllegalArgumentException { if (path.isEmpty() || !path.substring(0, 1).equals(DELIMITER)) { throw new IllegalArgumentException( <START> "Provided path is empty or does not have a leading delimiter: " + path); <END> } TrieNode curNode; try { curNode = findTrieNode(path, false); } catch (NoSuchElementException e) { return Collections.emptyMap(); } Map<String, String> resultMap = new HashMap<>(); Deque<TrieNode> nodeStack = new ArrayDeque<>(); nodeStack.push(curNode); while (!nodeStack.isEmpty()) { curNode = nodeStack.pop(); if (curNode.isLeaf()) { resultMap.put(curNode.getName(), curNode.getRealmAddress()); } else { for (TrieNode child : curNode.getChildren().values()) { nodeStack.push(child); } } } return resultMap; }</code><technical_language>Nit: add delimiter means "/"</technical_language>

Target:
public Map<String, String> getAllMappingUnderPath(String path) throws IllegalArgumentException { if (path.isEmpty() || !path.substring(0, 1).equals(DELIMITER)) { throw new IllegalArgumentException("Provided path is empty or does not have a leading \"" + DELIMITER + "\" character: " + path); } TrieNode curNode; try { curNode = findTrieNode(path, false); } catch (NoSuchElementException e) { return Collections.emptyMap(); } Map<String, String> resultMap = new HashMap<>(); Deque<TrieNode> nodeStack = new ArrayDeque<>(); nodeStack.push(curNode); while (!nodeStack.isEmpty()) { curNode = nodeStack.pop(); if (curNode.isShardingKey()) { resultMap.put(curNode.getPath(), curNode.getRealmAddress()); } else { for (TrieNode child : curNode.getChildren().values()) { nodeStack.push(child); } } } return resultMap; }
Source:
<code>private void runTasks() { while (true) { Runnable runnable = null; lock.lock(); try { if (availablePermits >= 0) { runnable = queue.poll(); } if (runnable == null) { availablePermits++; break; } } finally { lock.unlock(); } try { LogFactory.pushNDC(name, true); runnable.run(); } catch (Throwable t) { <START> log.error("Exception in task", t); <END> } finally { LogFactory.popNDC(true); } } }</code><technical_language>well, moved error Log</technical_language>

Target:
private void runTasks() { while (true) { Runnable runnable = null; lock.lock(); try { if (availablePermits >= 0) { runnable = queue.poll(); } if (runnable == null) { availablePermits++; break; } } finally { lock.unlock(); } try { NDC.push(name); runnable.run(); } catch (Throwable t) { log.error("Exception in task", t); } finally { NDC.pop(); } } }