auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return rangesTab.get(rowIndex).getColor(); case 1: return rangesTab.get(rowIndex).getAlias(); default: <START> return null; END> } }</code><technical_language>Moreover, returning null is safe ? a NullPointerException</technical_language>

Target:
public Object getValueAt(int rowIndex, int columnIndex) { switch (columnIndex) { case 0: return rangesTab.get(rowIndex).getColor(); case 1: return rangesTab.get(rowIndex).getAlias(); default: throw new ArrayIndexOutOfBoundsException(); } }
Source:
<code>public YouTubeAccessControl deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { YouTubeAccessControl accessControl = new YouTubeAccessControl(); JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("autoPlay")) { accessControl.setAutoPlay(getPermission(jsonObject.get("autoPlay") .getAsString())); } if (jsonObject.has("comment")) { accessControl.setAutoPlay(getPermission(jsonObject.get("comment") .getAsString())); } if (jsonObject.has("commentVote")) { accessControl.setAutoPlay(getPermission(jsonObject.get( "commentVote").getAsString())); } if (jsonObject.has("videoRespond")) { accessControl.setAutoPlay(getPermission(jsonObject.get( "videoRespond").getAsString())); } if (jsonObject.has("rate")) { accessControl.setAutoPlay(getPermission(jsonObject.get("rate") .getAsString())); } if (jsonObject.has("embed")) { accessControl.setAutoPlay(getPermission(jsonObject.get("embed") .getAsString())); } if (jsonObject.has("list")) { accessControl.setAutoPlay(getPermission(jsonObject.get("list") .getAsString())); } if (jsonObject.has("syndicate")) { accessControl.setAutoPlay(getPermission(jsonObject.get("syndicate") .getAsString())); <START> } <END> return accessControl; }</code><technical_language>this extracted a function? a fair amount of repetition here</technical_language>

Target:
public YouTubeAccessControl deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { YouTubeAccessControl accessControl = new YouTubeAccessControl(); return accessControl; }
Source:
<code>public long saveBox(Box box) throws IOException { if (boxStore != null) { if (box.getId() == AbstractBox.UNSAVED_ID) { try { boxStore.save(box); if (autoGenerateIdentificationBarcodes) { box.setIdentificationBarcode(box.getName() + "::" + box.getAlias()); } <START> namingScheme.generateNameFor(box); <END> validateNameOrThrow(box, namingScheme); return boxStore.save(box); } catch (MisoNamingException e) { throw new IOException("Invalid name for box", e); } } else { Box original = boxStore.get(box.getId()); original.setAlias(box.getAlias()); original.setDescription(box.getDescription()); original.setIdentificationBarcode(box.getIdentificationBarcode()); original.setSize(boxStore.getSizeById(box.getSize().getId())); original.setUse(boxStore.getUseById(box.getUse().getId())); Map<String, Boxable> contents = new HashMap<>(); for (Map.Entry<String, Boxable> entry : box.getBoxables().entrySet()) { saveBoxElement(contents, entry); } original.setBoxables(contents); return boxStore.save(box); } } else { throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); } }</code><technical_language>Need do this setting box's identificationBarcode of name</technical_language>

Target:
public long saveBox(Box box) throws IOException { if (boxStore != null) { return boxStore.save(box); } else { throw new IOException("No boxStore available. Check that it has been declared in the Spring config."); } }
Source:
<code>public OptimalAssignment calculate(ClusterModel clusterModel) throws HelixRebalanceException { OptimalAssignment optimalAssignment = new OptimalAssignment(); Map<String, Set<AssignableReplica>> replicasByResource = clusterModel.getAssignableReplicaMap(); List<AssignableNode> nodes = new ArrayList<>(clusterModel.getAssignableNodes().values()); List<AssignableReplica> orderedAssignableReplicas = replicasByResource.values().stream().flatMap(replicas -> replicas.stream()) .collect(Collectors.toList()); orderedAssignableReplicas.sort((o1, o2) -> { int priority1 = o1.getStatePriority(); int priority2 = o2.getStatePriority(); if (priority1 == priority2) { <START> return o1.getPartitionName().compareTo(o2.getPartitionName()); <END> } else { return priority1 - priority2; } }); for (AssignableReplica replica : orderedAssignableReplicas) { Optional<AssignableNode> maybeBestNode = getNodeWithHighestPoints(replica, nodes, clusterModel.getContext(), optimalAssignment); if (optimalAssignment.hasAnyFailure()) { String errorMessage = String.format( "Unable to find any available candidate node for partition %s; Fail reasons: %s", replica.getPartitionName(), optimalAssignment.getFailures()); throw new HelixRebalanceException(errorMessage, HelixRebalanceException.Type.FAILED_TO_CALCULATE); } maybeBestNode.ifPresent(node -> clusterModel .assign(replica.getResourceName(), replica.getPartitionName(), replica.getReplicaState(), node.getInstanceName())); } optimalAssignment.updateAssignments(clusterModel); return optimalAssignment; }</code><technical_language>strange read for future developers. a good reason, simply sorting partitionName get a result random? clear</technical_language>

Target:
public OptimalAssignment calculate(ClusterModel clusterModel) throws HelixRebalanceException { OptimalAssignment optimalAssignment = new OptimalAssignment(); List<AssignableNode> nodes = new ArrayList<>(clusterModel.getAssignableNodes().values()); for (AssignableReplica replica : getOrderedAssignableReplica(clusterModel)) { Optional<AssignableNode> maybeBestNode = getNodeWithHighestPoints(replica, nodes, clusterModel.getContext(), optimalAssignment); if (optimalAssignment.hasAnyFailure()) { String errorMessage = String.format( "Unable to find any available candidate node for partition %s; Fail reasons: %s", replica.getPartitionName(), optimalAssignment.getFailures()); throw new HelixRebalanceException(errorMessage, HelixRebalanceException.Type.FAILED_TO_CALCULATE); } maybeBestNode.ifPresent(node -> clusterModel .assign(replica.getResourceName(), replica.getPartitionName(), replica.getReplicaState(), node.getInstanceName())); } optimalAssignment.updateAssignments(clusterModel); return optimalAssignment; }
Source:
<code><START> abstract void serve() throws Exception; <END> abstract void serve(Writer out) throws Exception; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (Exception e) { throw new DotRuntimeException(e); } return out.toString(); }</code><technical_language>![MAJOR](<LINK_0> 'Severity: MAJOR') Define throw a dedicated exception instead of a generic one. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
abstract void serve() throws DotDataException, IOException, DotSecurityException; abstract void serve(Writer out) throws DotDataException, IOException, DotSecurityException; public final String eval() { StringWriter out = new StringWriter(4096); try { serve(out); } catch (DotDataException | IOException | DotSecurityException e) { throw new DotRuntimeException(e); } return out.toString(); }
Source:
<code>private static boolean isFailureToWrite( ClientException e ) { <START> return e.code().equals( "Neo.ClientError.Cluster.NotALeader" ) || <END> e.code().equals( "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase" ); }</code><technical_language>Warning: get ClientException code field this stage :)</technical_language>

Target:
private static boolean isFailureToWrite( ClientException e ) { String errorCode = e.code(); return Objects.equals( errorCode, "Neo.ClientError.Cluster.NotALeader" ) || Objects.equals( errorCode, "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase" ); }
Source:
<code><START> public BuildPlan getPlanById(List<IBuildPlan> plans, String id) { <END> if (id != null) { for (IBuildPlan plan : plans) { if (id.equals(plan.getId())) { return (BuildPlan) plan; } for (IBuildPlan childPlan : plan.getChildren()) { if (id.equals(childPlan.getId())) { return (BuildPlan) childPlan; } } } } return null; }</code><technical_language>this method supports layer of children</technical_language>

Target:
public BuildPlan getPlanById(List<IBuildPlan> plans, String id) { if (plans != null && id != null) { for (IBuildPlan plan : plans) { if (id.equals(plan.getId())) { return (BuildPlan) plan; } BuildPlan maybePlan = getPlanById(plan.getChildren(), id); if (maybePlan != null) { return maybePlan; } } } return null; }
Source:
<code>public void sendRequest() throws Exception { URLConnection connection = new URL("http://localhost:8181/cxf/HelloWorldSecurity") .openConnection(); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); InputStream fis = getClass().getClassLoader().getResourceAsStream("org/apache/camel/example/cxf/ws/request.xml"); System.out.println(fis.toString()); IOUtils.copy(fis, os); InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); <START> System.out.println("the response is =====>"); <END> System.out.println(baos.toString()); }</code><technical_language>response ..</technical_language>

Target:
public void sendRequest() throws Exception { URLConnection connection = new URL("http://localhost:8181/cxf/HelloWorldSecurity") .openConnection(); connection.setDoInput(true); connection.setDoOutput(true); OutputStream os = connection.getOutputStream(); InputStream fis = getClass().getClassLoader().getResourceAsStream("org/apache/camel/example/cxf/ws/request.xml"); IOUtils.copy(fis, os); InputStream is = connection.getInputStream(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); IOUtils.copy(is, baos); System.out.println(baos.toString()); }
Source:
<code>private Constraint coachStopLimit(ConstraintFactory constraintFactory) { return constraintFactory.from(BusStop.class) .filter(busStop -> busStop.getBus() instanceof Coach) .groupBy(busStop -> (Coach) busStop.getBus(), count()) .filter((coach, stopCount) -> stopCount > coach.getStopLimit()) <START> .penalizeLong("coachStopLimit", HardSoftLongScore.ofUninitialized(0, 1000000, 0), <END> (coach, stopCount) -> stopCount - coach.getStopLimit()); }</code><technical_language>HardSoftLongScore.ofHard(1000000)? Similarly in other constraints</technical_language>

Target:
private Constraint coachStopLimit(ConstraintFactory constraintFactory) { return constraintFactory.from(BusStop.class) .filter(busStop -> busStop.getBus() instanceof Coach) .groupBy(busStop -> (Coach) busStop.getBus(), count()) .filter((coach, stopCount) -> stopCount > coach.getStopLimit()) .penalizeLong("coachStopLimit", HardSoftLongScore.ofHard(1000_000), (coach, stopCount) -> stopCount - coach.getStopLimit()); }
Source:
<code>private void unzip(File dir, File zipFile) throws IOException { dir = dir.getAbsoluteFile(); ZipFile zip = new ZipFile(zipFile); @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = zip.getEntries(); try { while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); File f = new File(dir, e.getName()); if (e.isDirectory()) { <START> Files.createDirectories(f.toPath()); <END> } else { File p = f.getParentFile(); if (p != null) { Files.createDirectories(p.toPath()); } try (InputStream input = zip.getInputStream(e)) { IOUtils.copy(input, writing(f)); } try { FilePath target = new FilePath(f); int mode = e.getUnixMode(); if (mode!=0) target.chmod(mode); } catch (InterruptedException ex) { LOGGER.log(Level.WARNING, "unable to set permissions", ex); } f.setLastModified(e.getTime()); } } } finally { zip.close(); } }</code><technical_language>Util#toPath() created @dwnusbaum a while ago. is a risk of unhandled runtime InvalidPathException</technical_language>

Target:
private void unzip(File dir, File zipFile) throws IOException { dir = dir.getAbsoluteFile(); ZipFile zip = new ZipFile(zipFile); @SuppressWarnings("unchecked") Enumeration<ZipEntry> entries = zip.getEntries(); try { while (entries.hasMoreElements()) { ZipEntry e = entries.nextElement(); File f = new File(dir, e.getName()); if (e.isDirectory()) { mkdirs(f); } else { File p = f.getParentFile(); if (p != null) { mkdirs(p); } try (InputStream input = zip.getInputStream(e)) { IOUtils.copy(input, writing(f)); } try { FilePath target = new FilePath(f); int mode = e.getUnixMode(); if (mode!=0) target.chmod(mode); } catch (InterruptedException ex) { LOGGER.log(Level.WARNING, "unable to set permissions", ex); } f.setLastModified(e.getTime()); } } } finally { zip.close(); } }
Source:
<code>public TraceEventHandlerExecutionGraph(LttngKernelExecGraphProvider provider) { super(provider); <START> fKernel = NonNullUtils.checkNotNull(HashBasedTable.<@NonNull String, @NonNull Integer, @NonNull LttngWorker> create()); <END> fTcpNodes = new HashMap<>(); fMatchProcessing = new IMatchProcessingUnit() { @Override public void matchingEnded() { } @Override public int countMatches() { return 0; } @Override public void addMatch(@Nullable TmfEventDependency match) { if (match == null) { return; } @Nullable TmfVertex output = fTcpNodes.remove(match.getSourceEvent()); @Nullable TmfVertex input = fTcpNodes.remove(match.getDestinationEvent()); if (output != null && input != null) { output.linkVertical(input).setType(EdgeType.NETWORK); } } @Override public void init(Collection<ITmfTrace> fTraces) { } }; ITmfTrace trace = provider.getTrace(); fTcpMatching = new TmfEventMatching(Collections.singleton(trace), fMatchProcessing); fTcpMatching.initMatching(); }</code><technical_language>HashBasedTable.create() works</technical_language>

Target:
public TraceEventHandlerExecutionGraph(LttngKernelExecGraphProvider provider) { super(provider); fKernel = NonNullUtils.checkNotNull(HashBasedTable.create()); fTcpNodes = new HashMap<>(); fMatchProcessing = new IMatchProcessingUnit() { @Override public void matchingEnded() { } @Override public int countMatches() { return 0; } @Override public void addMatch(@Nullable TmfEventDependency match) { if (match == null) { return; } TmfVertex output = fTcpNodes.remove(match.getSourceEvent()); TmfVertex input = fTcpNodes.remove(match.getDestinationEvent()); if (output != null && input != null) { output.linkVertical(input).setType(EdgeType.NETWORK); } } @Override public void init(Collection<ITmfTrace> fTraces) { } }; ITmfTrace trace = provider.getTrace(); fTcpMatching = new TmfEventMatching(Collections.singleton(trace), fMatchProcessing); fTcpMatching.initMatching(); }
Source:
<code>private String getActualColumnName(String tableNameWithType, String columnName) { String[] splits = StringUtils.split(columnName, ".", 2); if (_enableCaseInsensitive) { if (splits.length == 2) { <START> if (tableNameWithType.equalsIgnoreCase(splits[0]) || TableNameBuilder.extractRawTableName(tableNameWithType) <END> .equalsIgnoreCase(splits[0])) { return _tableCache.getActualColumnName(tableNameWithType, splits[1]); } } return _tableCache.getActualColumnName(tableNameWithType, columnName); } else { if (splits.length == 2) { if (tableNameWithType.equals(splits[0]) || TableNameBuilder.extractRawTableName(tableNameWithType) .equals(splits[0])) { return splits[1]; } } } return columnName; }</code><technical_language>if need check. SELECT myTable_OFFLINE.colA ... impossible connector _OFFLINE is Pinot internal concept</technical_language>

Target:
private String getActualColumnName(String tableNameWithType, String columnName) { String[] splits = StringUtils.split(columnName, ".", 2); if (_enableCaseInsensitive) { if (splits.length == 2) { if (TableNameBuilder.extractRawTableName(tableNameWithType).equalsIgnoreCase(splits[0])) { return _tableCache.getActualColumnName(tableNameWithType, splits[1]); } } return _tableCache.getActualColumnName(tableNameWithType, columnName); } else { if (splits.length == 2) { if (TableNameBuilder.extractRawTableName(tableNameWithType).equals(splits[0])) { return splits[1]; } } } return columnName; }
Source:
<code>public RabbitTemplate rabbitTemplate(ConnectionFactory rabbitConnectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory); String converterBeanName = this.properties.getConverterBeanName(); if (StringUtils.hasText(converterBeanName)) { if (RabbitSinkProperties.JSON_CONVERTER.equals(converterBeanName)) { rabbitTemplate.setMessageConverter(jsonConverter()); } else { <START> rabbitTemplate.setMessageConverter(this.context.getBean(converterBeanName, MessageConverter.class)); <END> } } return rabbitTemplate; }</code><technical_language>I this better: @Value("#{${converterBeanName:null}}") private MessageConverter messageConverter; closer in XML config. :smile:</technical_language>

Target:
public RabbitTemplate rabbitTemplate(ConnectionFactory rabbitConnectionFactory) { RabbitTemplate rabbitTemplate = new RabbitTemplate(rabbitConnectionFactory); if (this.messageConverter != null) { rabbitTemplate.setMessageConverter(this.messageConverter); } return rabbitTemplate; }
Source:
<code>public void metricsText( @Suspended final AsyncResponse response, @QueryParam("group") String group, @Context final HttpServletRequest servletReq, final String query ) { final HttpContext httpContext = CoreHttpContextFactory.create(servletReq); <START> final QueryContext queryContext = QueryContextFactory.create(Optional.empty()); <END> queryLogger.logHttpQueryText(queryContext, query, httpContext); final Query q = this.query.newQueryFromString(query).build(); final QueryManager.Group g = this.query.useOptionalGroup(Optional.ofNullable(group)); final AsyncFuture<QueryResult> callback = g.query(q, queryContext); bindMetricsResponse(response, callback, queryContext); }</code><technical_language>If move factory QueryContext this replaced QueryContext.empty();</technical_language>

Target:
public void metricsText( @Suspended final AsyncResponse response, @QueryParam("group") String group, @Context final HttpServletRequest servletReq, final String query ) { final HttpContext httpContext = CoreHttpContextFactory.create(servletReq); final QueryContext queryContext = QueryContext.empty(); queryLogger.logHttpQueryText(queryContext, query, httpContext); final Query q = this.query.newQueryFromString(query).build(); final QueryManager.Group g = this.query.useOptionalGroup(Optional.ofNullable(group)); final AsyncFuture<QueryResult> callback = g.query(q, queryContext); bindMetricsResponse(response, callback, queryContext); }
Source:
<code>public void run() { <START> _logHandler.setUpContext(_process, _context); <END> while (_running) { try { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in bolt message: " + shellMsg); } setHeartbeat(); switch (command) { case "ack": handleAck(shellMsg.getId()); break; case "fail": handleFail(shellMsg.getId()); break; case "error": handleError(shellMsg.getMsg()); break; case "log": _logHandler.log(shellMsg); break; case "emit": handleEmit(shellMsg); break; case "metrics": handleMetrics(shellMsg); break; } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } }</code><technical_language>This is effectively one-time setup, if want one-time setup, initialize in prepare(), more familiar initializing in it</technical_language>

Target:
public void run() { while (_running) { try { ShellMsg shellMsg = _process.readShellMsg(); String command = shellMsg.getCommand(); if (command == null) { throw new IllegalArgumentException("Command not found in bolt message: " + shellMsg); } setHeartbeat(); switch (command) { case "ack": handleAck(shellMsg.getId()); break; case "fail": handleFail(shellMsg.getId()); break; case "error": handleError(shellMsg.getMsg()); break; case "log": _logHandler.log(shellMsg); break; case "emit": handleEmit(shellMsg); break; case "metrics": handleMetrics(shellMsg); break; } } catch (InterruptedException e) { } catch (Throwable t) { die(t); } } }
Source:
<code>public Supplier<PrimitiveService> serviceFactory() { <START> return null; <END> }</code><technical_language>Intentional</technical_language>

Target:
public Supplier<PrimitiveService> serviceFactory() { throw new UnsupportedOperationException(); }
Source:
<code>public static boolean isSystemDarkTheme () { boolean isDarkTheme = false; if (OS.WIN32_VERSION >= OS.VERSION (10, 0)) { TCHAR key = new TCHAR (0, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", true); long phkResult = new long [1]; boolean regKeyFound = false; if (OS.RegOpenKeyEx(OS.HKEY_CURRENT_USER, key, 0, OS.KEY_READ, phkResult) == 0) { regKeyFound = true; } else if (OS.RegOpenKeyEx(OS.HKEY_LOCAL_MACHINE, key, 0, OS.KEY_READ, phkResult) == 0) { regKeyFound = true; } if (regKeyFound) { int lpcbData = new int [1]; TCHAR buffer = new TCHAR (0, "AppsUseLightTheme", true); <START> int result = OS.RegQueryValueEx (phkResult [0], buffer, 0, null, (TCHAR)null, lpcbData); if (result == 0) { <END> int[] lpData = new int[1]; result = OS.RegQueryValueEx(phkResult[0], buffer, 0, null, lpData, lpcbData); if (result == 0) { isDarkTheme = (lpData[0] == 0); } } OS.RegCloseKey (phkResult [0]); } } return isDarkTheme; }</code><technical_language>I understand this is copy&pasted other places. 'RegQueryValueEx' is called times measure amount of memory needed, allocate query actual contents. expecting a DWORD here, set lpcbData[0] 4 remove highlighted code. PS: a good idea extract a function this, OS.readRegistryDword(OS.HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", "AppsUseLightTheme")</technical_language>

Target:
public static boolean isSystemDarkTheme () { boolean isDarkTheme = false; if (OS.WIN32_VERSION >= OS.VERSION (10, 0)) { TCHAR key = new TCHAR (0, "Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", true); long phkResult = new long [1]; if (OS.RegOpenKeyEx(OS.HKEY_CURRENT_USER, key, 0, OS.KEY_READ, phkResult) == 0) { int[] lpcbData = new int[] { 4 }; TCHAR buffer = new TCHAR(0, "AppsUseLightTheme", true); int[] lpData = new int[1]; int result = OS.RegQueryValueEx(phkResult[0], buffer, 0, null, lpData, lpcbData); if (result == 0) { isDarkTheme = (lpData[0] == 0); } OS.RegCloseKey(phkResult[0]); } } return isDarkTheme; }
Source:
<code>private void checkFieldType(String fieldName, long columnIndex, RealmFieldType expectedType) { RealmFieldType columnType = proxyState.getRow$realm().getColumnType(columnIndex); if (columnType != RealmFieldType.BOOLEAN) { String indefiniteWowel = ""; if (expectedType == RealmFieldType.INTEGER || expectedType == RealmFieldType.LIST) { indefiniteWowel = "n"; } throw new IllegalArgumentException(String.format("'%s' is not a%s '%s', but a%s '%s'.", <START> fieldName, indefiniteWowel, expectedType, indefiniteWowel, columnType)); <END> } }</code><technical_language>need indefiniteWowel1 indefiniteWovel2 _two_ types</technical_language>

Target:
private void checkFieldType(String fieldName, long columnIndex, RealmFieldType expectedType) { RealmFieldType columnType = proxyState.getRow$realm().getColumnType(columnIndex); if (columnType != expectedType) { String indefiniteVowel = ""; if (expectedType == RealmFieldType.INTEGER || expectedType == RealmFieldType.LIST) { indefiniteVowel = "n"; } throw new IllegalArgumentException(String.format("'%s' is not a%s '%s', but a%s '%s'.", fieldName, indefiniteVowel, expectedType, indefiniteVowel, columnType)); } }
Source:
<code>public boolean isAllowedContents(Object object) { boolean result = false; if (object instanceof Property) { final Property prop = (Property) object; Element owner = prop.getOwner(); result = owner instanceof Stereotype; <START> if (result) { <END> result = false; while(owner.getOwner() instanceof Package && !result){ result = owner.getOwner() instanceof Profile; owner = owner.getOwner(); } if (result) { result = EMFHelper.isReadOnly(prop); } } } return result; }</code><technical_language>of "result" is a strange here. need a variable test instanceof</technical_language>

Target:
public boolean isAllowedContents(Object object) { boolean result = false; if (object instanceof Property) { final Property prop = (Property) object; Element owner = prop.getOwner(); if (owner instanceof Stereotype) { while(owner.getOwner() instanceof Package && !result){ owner = owner.getOwner(); result = owner instanceof Profile; } if (result) { result = EMFHelper.isReadOnly(prop); } } } return result; }
Source:
<code>public String <START> toString() <END> { return new String(fValue) + (fIsUDLIntegral ? new String(fSuffix) : ""); }</code><technical_language>Reliance toString method for debugging is a dangerous practice. is preferable introduce a specialized method methods defined semantics</technical_language>

Target:
public String toString() { return new String(getLiteral()); }
Source:
<code>public int read(byte[] bytes, int offset, int length) throws IOException { <START> if (length == 0) { <END> return 0; } int count = Math.min(byteBuffer.remaining(), length); if (count == 0) { return -1; } byteBuffer.get(bytes, offset, count); return count; }</code><technical_language>this class tests</technical_language>

Target:
public int read(byte[] bytes, int offset, int length) throws IOException { if (bytes == null) { throw new NullPointerException(); } else if (offset < 0 || length < 0 || length > bytes.length - offset) { throw new IndexOutOfBoundsException(); } else if (length == 0) { return 0; } int count = Math.min(byteBuffer.remaining(), length); if (count == 0) { return -1; } byteBuffer.get(bytes, offset, count); return count; }
Source:
<code>public void testUnbufferStreamStatistics() throws IOException { describe("testUnbufferStreamStatistics"); Configuration conf = createConfiguration(); S3AFileSystem fs = new S3AFileSystem(); fs.initialize(getFileSystem().getUri(), conf); FSDataInputStream inputStream = null; try { inputStream = fs.open(dest); assertEquals(0, fs.getInstrumentation().getCounterValue(STREAM_SEEK_BYTES_READ)); assertEquals(8, inputStream.read(new byte[8])); inputStream.unbuffer(); assertEquals(8, fs.getInstrumentation().getCounterValue(STREAM_SEEK_BYTES_READ)); assertEquals(4, inputStream.read(new byte[4])); inputStream.unbuffer(); assertEquals(12, fs.getInstrumentation().getCounterValue(STREAM_SEEK_BYTES_READ)); } finally { <START> if (inputStream != null) { <END> inputStream.close(); } } assertEquals(12, fs.getInstrumentation().getCounterValue(STREAM_SEEK_BYTES_READ)); assertNotNull(inputStream); assertEquals(12, ((S3AInputStream) inputStream.getWrappedStream()) .getS3AStreamStatistics().bytesRead); }</code><technical_language>IOUtils.closeStream</technical_language>

Target:
public void testUnbufferStreamStatistics() throws IOException { describe("testUnbufferStreamStatistics"); S3ATestUtils.MetricDiff bytesRead = new S3ATestUtils.MetricDiff( getFileSystem(), STREAM_SEEK_BYTES_READ); FSDataInputStream inputStream = null; try { inputStream = getFileSystem().open(dest); readAndAssertBytesRead(inputStream, 8); inputStream.unbuffer(); bytesRead.assertDiffEquals(8); readAndAssertBytesRead(inputStream, 4); inputStream.unbuffer(); bytesRead.assertDiffEquals(12); } finally { IOUtils.closeStream(inputStream); } bytesRead.assertDiffEquals(12); assertEquals("S3AInputStream statistics were not updated properly", 12, ((S3AInputStream) inputStream.getWrappedStream()) .getS3AStreamStatistics().bytesRead); }
Source:
<code>public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_settings: return true; <START> case android.R.id.home: <END> this.finish(); return true; } return super.onOptionsItemSelected(item); }</code><technical_language>Instead of finish(), set parent of activity in manifest MITMainActivity, navigate properly home activity</technical_language>

Target:
public boolean onOptionsItemSelected(MenuItem item) { int id = item.getItemId(); switch (id) { case R.id.action_settings: return true; case android.R.id.home: this.startActivity(SharedActivityManager.createHomeJumpActivity(this)); this.finish(); return true; } return super.onOptionsItemSelected(item); }
Source:
<code>public void invalidCollectionName() { <START> assertThrows(RuntimeException.class, () -> subject.areCollectionsUp(Collections.singletonList("foo"))); <END> }</code><technical_language>Remember [AssertJ check for exceptions](<LINK_0> too</technical_language>

Target:
public void invalidCollectionName() { assertThatExceptionOfType(RuntimeException.class).isThrownBy(() -> subject.areCollectionsUp(Collections.singletonList("foo"))); }
Source:
<code>public void testResponseStreamCannotBeReadTwice() throws Exception { final RestResponse response = getStreamTestResponse(); try { InputStream in = response.asInputStream(); inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } <START> try (InputStream in = response.asInputStream()) { <END> assertNull("The InputStream should be null when trying to read it a second time", in); } catch (IOException e) { fail("An IOException should not have been thrown"); } finally { response.consumeQuietly(); } }</code><technical_language>more instance of Java 7 syntax replaced</technical_language>

Target:
public void testResponseStreamCannotBeReadTwice() throws Exception { final RestResponse response = getStreamTestResponse(); try { final InputStream in = response.asInputStream(); inputStreamToString(in); } catch (IOException e) { fail("The InputStream should be readable and an IOException should not have been thrown"); } try { response.asInputStream(); fail("An IOException should have been thrown while trying to read the InputStream a second time"); } catch (IOException e) { } finally { response.consumeQuietly(); } }
Source:
<code>protected void findLastPartition(HCatClient hcatClient, String stream) throws HCatException { List<HCatPartition> hCatPartitionList = hcatClient.getPartitions( Conduit.getHcatDBName(), getTableName(stream)); if (hCatPartitionList.isEmpty()) { LOG.info("No partitions present for " + stream + " stream. "); <START> updateLastAddedPartitionMap(stream, (long) -1); <END> return; } Collections.sort(hCatPartitionList, new HCatPartitionComparator()); HCatPartition lastHcatPartition = hCatPartitionList.get(hCatPartitionList.size()-1); Date lastAddedPartitionDate = getTimeStampFromHCatPartition( lastHcatPartition.getLocation(), stream); if (lastAddedPartitionDate != null) { LOG.info("Last added partition timetamp : " + lastAddedPartitionDate.getTime() + " for stream " + stream); updateLastAddedPartitionMap(stream, lastAddedPartitionDate.getTime()); } else { updateLastAddedPartitionMap(stream, (long) -1); } }</code><technical_language>instead of putting -1,make a constant "EMPTY PARTITION LIST=-1" everywhere,for putting,for checking etc</technical_language>

Target:
public void findLastPartition(HCatClient hcatClient, String stream) throws HCatException { String tableName = getTableName(stream); List<HCatPartition> hCatPartitionList = hcatClient.getPartitions( Conduit.getHcatDBName(), tableName); if (hCatPartitionList.isEmpty()) { LOG.info("No partitions present for " + stream + " stream. "); updateLastAddedPartitionMap(tableName, EMPTY_PARTITION_LIST); return; } Collections.sort(hCatPartitionList, new HCatPartitionComparator()); HCatPartition lastHcatPartition = hCatPartitionList.get(hCatPartitionList.size()-1); Date lastAddedPartitionDate = getTimeStampFromHCatPartition( lastHcatPartition.getLocation(), stream); if (lastAddedPartitionDate != null) { LOG.info("Last added partition timetamp : " + lastAddedPartitionDate.getTime() + " for stream " + stream); updateLastAddedPartitionMap(tableName, lastAddedPartitionDate.getTime()); } else { updateLastAddedPartitionMap(tableName, EMPTY_PARTITION_LIST); } }
Source:
<code>public void deployStream(String name, Map<String, String> deploymentProperties) { if (deploymentProperties == null) { deploymentProperties = new HashMap<>(); } StreamDefinition streamDefinition = this.streamDefinitionRepository.findOne(name); if (streamDefinition == null) { throw new NoSuchStreamDefinitionException(name); } DeploymentState status = this.doCalculateStreamState(name); if (DeploymentState.deployed == status) { throw new StreamAlreadyDeployedException(name); } else if (DeploymentState.deploying == status) { throw new StreamAlreadyDeployingException(name); } doDeployStream(streamDefinition, deploymentProperties); final Map<String, Object> auditedData = new HashMap<>(2); <START> auditedData.put("streamDefinitionDslText", streamDefinition.getDslText()); <END> auditedData.put("deploymentProperties", deploymentProperties); auditRecordService.populateAndSaveAuditRecord( AuditActionType.DEPLOY, AuditOperationType.STREAM_DEFINITIONS, streamDefinition.getName(), auditedData); }</code><technical_language>constant names for fields useful for other systems built audit data</technical_language>

Target:
public void deployStream(String name, Map<String, String> deploymentProperties) { if (deploymentProperties == null) { deploymentProperties = new HashMap<>(); } StreamDefinition streamDefinition = this.streamDefinitionRepository.findOne(name); if (streamDefinition == null) { throw new NoSuchStreamDefinitionException(name); } DeploymentState status = this.doCalculateStreamState(name); if (DeploymentState.deployed == status) { throw new StreamAlreadyDeployedException(name); } else if (DeploymentState.deploying == status) { throw new StreamAlreadyDeployingException(name); } doDeployStream(streamDefinition, deploymentProperties); final Map<String, Object> auditedData = new HashMap<>(2); auditedData.put(STREAM_DEFINITION_DSL_TEXT, streamDefinition.getDslText()); auditedData.put(DEPLOYMENT_PROPERTIES, deploymentProperties); auditRecordService.populateAndSaveAuditRecordUsingMapData( AuditOperationType.STREAM, AuditActionType.DEPLOY, streamDefinition.getName(), auditedData); }
Source:
<code>public static Optional<List<List<String>>> getPartitionList(Map<String, Object> properties) { List<List<String>> partitions = (List<List<String>>) properties.get(PARTITION_LIST_PROPERTY); <START> return partitions == null ? Optional.empty() : Optional.of(ImmutableList.copyOf(partitions)); <END> }</code><technical_language>need another ImmutableList.copyOf. this parsing</technical_language>

Target:
public static Optional<List<List<String>>> getPartitionList(Map<String, Object> properties) { List<List<String>> partitions = (List<List<String>>) properties.get(PARTITIONS_PROPERTY); return partitions == null ? Optional.empty() : Optional.of(partitions); }
Source:
<code>protected TmfTimeRange getSignalTimeRange(ITmfTimestamp startTime) { fLock.lock(); <START> TmfTimeRange currentRange = TmfTraceManager.getInstance().getCurrentRange(); <END> try { long offset = fTrace == null ? 0 : currentRange.getEndTime().getDelta(currentRange.getStartTime()).normalize(0, startTime.getScale()).getValue(); TmfTimestamp initialEndOfWindow = new TmfTimestamp(startTime.getValue() + offset, startTime.getScale(), startTime.getPrecision()); return new TmfTimeRange(startTime, initialEndOfWindow); } finally { fLock.unlock(); } }</code><technical_language>move this in try block. in case is exception in trace manager unlock is called. in case</technical_language>

Target:
protected TmfTimeRange getSignalTimeRange(ITmfTimestamp startTime) { fLock.lock(); try { TmfTimeRange currentRange = TmfTraceManager.getInstance().getCurrentRange(); long offset = fTrace == null ? 0 : currentRange.getEndTime().getDelta(currentRange.getStartTime()).normalize(0, startTime.getScale()).getValue(); TmfTimestamp initialEndOfWindow = new TmfTimestamp(startTime.getValue() + offset, startTime.getScale(), startTime.getPrecision()); return new TmfTimeRange(startTime, initialEndOfWindow); } finally { fLock.unlock(); } }
Source:
<code>private String getExecutionPlanName(String alertType, String queryName) { if ("Traffic".equals(alertType)) { return "Geo-ExecutionPlan-Traffic_" + queryName + "_alert"; } else { <START> if (alertType.equals("Speed")) { <END> return "Geo-ExecutionPlan-" + alertType + "---" + "_alert"; } return "Geo-ExecutionPlan-" + alertType + "_" + queryName + "---" + "_alert"; } }</code><technical_language>instead if("Speed".equals(alertType)) avoid NPE</technical_language>

Target:
private String getExecutionPlanName(String alertType, String queryName) { if ("Traffic".equals(alertType)) { return "Geo-ExecutionPlan-Traffic_" + queryName + "_alert"; } else { if ("Speed".equals(alertType)) { return "Geo-ExecutionPlan-" + alertType + "---" + "_alert"; } return "Geo-ExecutionPlan-" + alertType + "_" + queryName + "---" + "_alert"; } }
Source:
<code>protected Map<String, String> getFileSystemProperties(BatchSourceContext context) { Map<String, String> properties = new HashMap<>(config.getFileSystemProperties()); if (config.shouldCopyHeader()) { properties.put(PathTrackingInputFormat.COPY_HEADER, "true"); } <START> if (config.getFileEncoding() != null) { <END> properties.put(PathTrackingInputFormat.SOURCE_FILE_ENCODING, config.getFileEncoding()); } return properties; }</code><technical_language>UTF-8 null here? I missing it</technical_language>

Target:
protected Map<String, String> getFileSystemProperties(BatchSourceContext context) { Map<String, String> properties = new HashMap<>(config.getFileSystemProperties()); if (config.shouldCopyHeader()) { properties.put(PathTrackingInputFormat.COPY_HEADER, "true"); } return properties; }
Source:
<code>private void cleanUpProgramState(CFG.Block block) { <START> programState = ProgramState.cleanupDeadSymbols(programState, liveVariables.getOut(block)); <END> programState = programState.cleanupConstraints(); }</code><technical_language>a static method ? for constancy I static</technical_language>

Target:
private void cleanUpProgramState(CFG.Block block) { if (cleanup) { programState = programState.cleanupDeadSymbols(liveVariables.getOut(block)); programState = programState.cleanupConstraints(); } }
Source:
<code>public LdapReturnValueBase execute() { try { log.debugFormat("Running LDAP command: {0}", getClass().getName()); String loginNameForKerberos = LdapBrokerUtils.modifyLoginNameForKerberos(getLoginName(), getAuthenticationDomain()); LdapCredentials ldapCredentials = new LdapCredentials(loginNameForKerberos, getPassword()); DirectorySearcher directorySearcher = new DirectorySearcher(ldapCredentials); executeQuery(directorySearcher); } catch (RuntimeException e) { <START> log.errorFormat(String.format("Failed to run command %s. Domain is %s. User is %s.", <END> getClass().getSimpleName(), getDomain(), getLoginName())); _ldapReturnValue.setExceptionString(VdcBllMessages.FAILED_TO_RUN_LDAP_QUERY.name()); } return _ldapReturnValue; }</code><technical_language>redundant format</technical_language>

Target:
public LdapReturnValueBase execute() { try { log.debugFormat("Running LDAP command: {0}", getClass().getName()); String loginNameForKerberos = LdapBrokerUtils.modifyLoginNameForKerberos(getLoginName(), getAuthenticationDomain()); LdapCredentials ldapCredentials = new LdapCredentials(loginNameForKerberos, getPassword()); DirectorySearcher directorySearcher = new DirectorySearcher(ldapCredentials); executeQuery(directorySearcher); } catch (RuntimeException e) { log.error(String.format("Failed to run command %s. Domain is %s. User is %s.", getClass().getSimpleName(), getDomain(), getLoginName())); _ldapReturnValue.setExceptionString(VdcBllMessages.FAILED_TO_RUN_LDAP_QUERY.name()); } return _ldapReturnValue; }
Source:
<code>protected String getTitle() { <START> return "Developer Options"; <END> }</code><technical_language>I realize this this before, this title localizable of others</technical_language>

Target:
protected String getTitle() { return Localization.get("settings.developer.title"); }
Source:
<code>public <T> Subscription addOnRemovedListener(final Class<T> beanClass, final BeanRemovedListener<? super T> listener) { DolphinUtils.assertIsDolphinBean(beanClass); <START> if (beanRemovedListenerMap.containsKey(beanClass)) { <END> beanRemovedListenerMap.get(beanClass).add(listener); } else { beanRemovedListenerMap.put(beanClass, Arrays.asList(listener)); } return () -> { if (beanRemovedListenerMap.containsKey(beanClass)) { beanRemovedListenerMap.get(beanClass).remove(listener); } }; }</code><technical_language>Map in Java8 provides nice new methods for this pattern ;)</technical_language>

Target:
public <T> Subscription addOnRemovedListener(final Class<T> beanClass, final BeanRemovedListener<? super T> listener) { DolphinUtils.assertIsDolphinBean(beanClass); beanRemovedListenerMap.computeIfAbsent(beanClass, s -> new ArrayList()).add(listener); return () -> { if (beanRemovedListenerMap.containsKey(beanClass)) { beanRemovedListenerMap.get(beanClass).remove(listener); } }; }
Source:
<code><START> protected void buildImage( <END> DockerContainerConfig containerConfig, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws InternalInfrastructureException { File workDir = null; try { BuildImageParams buildImageParams; if (containerConfig.getBuild() != null && containerConfig.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(containerConfig.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(containerConfig.getBuild().getContext()) .withDockerfile(containerConfig.getBuild().getDockerfilePath()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(containerConfig.getMemLimit()) .withMemorySwapLimit(-1) .withBuildArgs(containerConfig.getBuild().getArgs()); dockerConnector.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new InternalInfrastructureException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } }</code><technical_language>is supposed overridden</technical_language>

Target:
private void buildImage( DockerContainerConfig containerConfig, String machineImageName, boolean doForcePullOnBuild, ProgressMonitor progressMonitor) throws InternalInfrastructureException { File workDir = null; try { BuildImageParams buildImageParams; if (containerConfig.getBuild() != null && containerConfig.getBuild().getDockerfileContent() != null) { workDir = Files.createTempDirectory(null).toFile(); final File dockerfileFile = new File(workDir, "Dockerfile"); try (FileWriter output = new FileWriter(dockerfileFile)) { output.append(containerConfig.getBuild().getDockerfileContent()); } buildImageParams = BuildImageParams.create(dockerfileFile); } else { buildImageParams = BuildImageParams.create(containerConfig.getBuild().getContext()) .withDockerfile(containerConfig.getBuild().getDockerfilePath()); } buildImageParams .withForceRemoveIntermediateContainers(true) .withRepository(machineImageName) .withAuthConfigs(dockerCredentials.getCredentials()) .withDoForcePull(doForcePullOnBuild) .withMemoryLimit(containerConfig.getMemLimit()) .withMemorySwapLimit(-1) .withBuildArgs(containerConfig.getBuild().getArgs()); dockerConnector.buildImage(buildImageParams, progressMonitor); } catch (IOException e) { throw new InternalInfrastructureException(e.getLocalizedMessage(), e); } finally { if (workDir != null) { FileCleaner.addFile(workDir); } } }
Source:
<code>public static AsyncLockClient create(MetricRegistry metricRegistry, List<String> hosts) { <START> return new AsyncLockClient(TimelockUtils.createClient(metricRegistry, hosts, NamespaceAwareTimelockRpcClient.class)); <END> }</code><technical_language>fussed, do want TimelockRpcClient.class</technical_language>

Target:
public static AsyncLockClient create(MetricRegistry metricRegistry, List<String> hosts) { return new AsyncLockClient(TimelockUtils.createClient(metricRegistry, hosts, NamespacedTimelockRpcClient.class)); }
Source:
<code>public static void maybeShowEditDescriptionUnlockNotification(@NonNull Context context, boolean forced) { if (!WikipediaApp.getInstance().isAnyActivityResumed() && !Prefs.isSuggestedEditsAddDescriptionsMessageShown() || forced) { <START> Prefs.setSuggestedEditsAddDescriptionsMessageShown(true); <END> SuggestedEditsFunnel.get(Constants.InvokeSource.NOTIFICATION).pause(); Intent intent = EditTasksActivity.newIntent(context, Constants.InvokeSource.EDIT_FEED_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, context.getString(R.string.suggested_edits_unlock_notification_button), pendingIntent); NotificationPresenter.showNotification(context, builder, 0, context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_title), context.getString(R.string.suggested_edits_unlock_notification_text), context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_big_text), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }</code><technical_language>I I understand purpose of this new preference. Do need it? prevents notification (or dialog) shown more once. if user logs out, another user logs in, knowing notifications? is understanding wrong</technical_language>

Target:
public static void maybeShowEditDescriptionUnlockNotification(@NonNull Context context, boolean forced) { if (!WikipediaApp.getInstance().isAnyActivityResumed() || forced) { SuggestedEditsFunnel.get(Constants.InvokeSource.NOTIFICATION).pause(); Intent intent = EditTasksActivity.newIntent(context, Constants.InvokeSource.EDIT_FEED_TITLE_DESC); NotificationCompat.Builder builder = NotificationPresenter.getDefaultBuilder(context); PendingIntent pendingIntent = PendingIntent.getActivity(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); builder.addAction(0, context.getString(R.string.suggested_edits_unlock_notification_button), pendingIntent); NotificationPresenter.showNotification(context, builder, 0, context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_title), context.getString(R.string.suggested_edits_unlock_notification_text), context.getString(R.string.suggested_edits_unlock_add_descriptions_notification_big_text), R.drawable.ic_mode_edit_white_24dp, R.color.accent50, intent); } }
Source:
<code>public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); <START> Path folder = Paths.get(System.getProperty("user.dir") , "testResources"); <END> ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(exercises.size(), 152); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }</code><technical_language>Is this I is -- a normal directory temp directory - temp folders..</technical_language>

Target:
public void downloadAllExercises() throws Exception { CoreTestSettings settings1 = createSettingsAndWiremock(); core = new TmcCore(settings1); Path folder = Paths.get(System.getProperty("user.dir") + "/testResources/"); ListenableFuture<List<Exercise>> download = core.downloadExercises(folder, 35, null); List<Exercise> exercises = download.get(); Path exercisePath = folder.resolve("2013_ohpeJaOhja/viikko1/Viikko1_001.Nimi"); assertEquals(153, exercises.size()); assertTrue(Files.exists(exercisePath)); FileUtils.deleteDirectory(exercisePath.toFile()); assertFalse(Files.exists(exercisePath)); }
Source:
<code>public int hashCode() { <START> int result = 17; <END> result = 31 * result + edgeId.hashCode(); if (outputTag != null) { result = 31 * result + outputTag.hashCode(); } return result; }</code><technical_language>This Objects.hash()</technical_language>

Target:
public int hashCode() { return Objects.hash(edgeId, outputTag); }