auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { <START> NativeImageLoader loader = new NativeImageLoader(224, 224, 3); <END> INDArray image = loader.asMatrix(stream); DataNormalization scaler = new VGG16ImagePreProcessor(); scaler.transform(image); INDArray[] output = model.output(false, image); String modelOutput = TrainedModels.VGG16.decodePredictions(output[0]); modelOutput = modelOutput.replace("Predictions for batch :\n", ""); modelOutput = modelOutput.replace("%", ""); String objs[] = modelOutput.split("\n"); List<RecognisedObject> objects = new ArrayList<>(); for (String obj : objs) { String data[]; data = obj.split(","); double confidence = Double.parseDouble(data[0]); objects.add(new RecognisedObject(data[1].trim(), "eng", data[1].trim(), confidence)); } return objects; }</code><technical_language>loader object declared a member variable reused here</technical_language>

Target:
public List<RecognisedObject> recognise(InputStream stream, ContentHandler handler, Metadata metadata, ParseContext context) throws IOException, SAXException, TikaException { INDArray image = imageLoader.asMatrix(stream); preProcessor.transform(image); INDArray[] output = model.output(false, image); return predict(output[0]); }
Source:
<code>public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); try { Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); <START> Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); <END> return attribute; } catch(WrongReferenceAttributeValueException ex) { return attribute; } }</code><technical_language>here: return Utils.copyAttribute....</technical_language>

Target:
public Attribute getAttributeValue(PerunSessionImpl sess, Facility facility, AttributeDefinition attributeDefinition) throws InternalErrorException { Attribute attribute = new Attribute(attributeDefinition); Attribute gidNamespaceAttribute = getUnixGIDNamespaceAttribute(sess, facility); if(gidNamespaceAttribute.getValue() == null) return attribute; Attribute namespaceMaxGidAttribute = getNamespaceMaxGidAttribute(sess, (String) gidNamespaceAttribute.getValue()); return Utils.copyAttributeToVirtualAttributeWithValue(namespaceMaxGidAttribute, attribute); }
Source:
<code>public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 300: <START> return; <END> case 400: break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } command.setException(exception); }</code><technical_language>add a check this applies version negotiation requests, propagate exception otherwise</technical_language>

Target:
public void handleError(HttpCommand command, HttpResponse response) { byte[] data = closeClientButKeepContentStream(response); String message = data != null ? new String(data) : null; Exception exception = message != null ? new HttpResponseException(command, response, message) : new HttpResponseException(command, response); message = message != null ? message : String.format("%s -> %s", command.getCurrentRequest().getRequestLine(), response.getStatusLine()); switch (response.getStatusCode()) { case 300: if (command.getCurrentRequest().getFirstHeaderOrNull(ZoneToEndpointNegotiateVersion.VERSION_NEGOTIATION_HEADER) != null) { return; } break; case 400: break; case 401: case 403: exception = new AuthorizationException(message, exception); break; case 404: if (!command.getCurrentRequest().getMethod().equals("DELETE")) { exception = new ResourceNotFoundException(message, exception); } break; } command.setException(exception); }
Source:
<code>public Queue replies() { <START> return new AnonymousQueue(new AnonymousQueue.Base64UrlNamingStrategy()); <END> }</code><technical_language>I revert this change AnonymousQueue is Base64 default</technical_language>

Target:
public Queue replies() { return new AnonymousQueue(); }
Source:
<code>private void addTags( List<Tag> tags ) { this.reportModel.addTags( tags ); <START> this.scenarioModel.addTags( tags ); <END> }</code><technical_language>do add tags reportModel scenarioModel</technical_language>

Target:
private void addTags( List<Tag> tags ) { if( tags.isEmpty() ) { return; } if( reportModel != null ) { this.reportModel.addTags( tags ); } if( scenarioModel != null ) { this.scenarioModel.addTags( tags ); } }
Source:
<code>public void InteractiveMaps_031_PalantirSetPlayerPositionOutOfMap() { InteractiveMapPageObject selectedMap = new InteractiveMapPageObject(driver); <START> selectedMap.openMap(wikiURL, 3); <END> selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = new PalantirContent(); handle = poi.setAndVerifyPlayerPosition(9300, 15000, 3, true); poi.verifyWrongPlayerPos(handle.success, handle.responseCode, handle.message); poi.verifyPoiNotAppearOnMap(); }</code><technical_language>Suggest move 2nd param a class variable I other tests value</technical_language>

Target:
public void InteractiveMaps_031_PalantirSetPlayerPositionOutOfMap() { InteractiveMapsPageObject specialMap = new InteractiveMapsPageObject(driver); InteractiveMapPageObject selectedMap = specialMap.openMap(wikiURL, PalantirContent.PALANTIR_MAP); selectedMap.verifyMapOpened(); PalantirComponentObject poi = new PalantirComponentObject(driver); PalantirContent handle = poi.setAndVerifyPlayerPosition(9300, 15000, 3, true); poi.verifyWrongPlayerPos(handle); poi.verifyPoiNotAppearOnMap(); }
Source:
<code>public void run() { ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); <START> if (!(sysLoader instanceof URLClassLoader)) { <END> return; } File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, file.toURI().toURL()); } catch (ReflectiveOperationException | MalformedURLException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }</code><technical_language>Add a severe logging message describing issue server owners (and need downgrade for now)</technical_language>

Target:
public void run() { if (nonUrlClassLoader) { return; } ClassLoader sysLoader = ClassLoader.getSystemClassLoader(); if (!(sysLoader instanceof URLClassLoader)) { nonUrlClassLoader = true; GlowServer.logger.severe("This JVM isn't fully supported. Please use Oracle or" + " OpenJDK 8, not 9. (System class loader must be a URLClassLoader.)"); return; } File file = new File(directory, getLibrary()); if (!checksum(file, checksum)) { GlowServer.logger.info("Downloading " + library + ' ' + version + "..."); try { URL downloadUrl = new URL(repository + group.replace('.', '/') + '/' + library + '/' + version + '/' + library + '-' + version + ".jar"); HttpsURLConnection connection = (HttpsURLConnection) downloadUrl.openConnection(); connection.setRequestProperty("User-Agent", "Mozilla/5.0"); try (ReadableByteChannel input = Channels.newChannel(connection.getInputStream()); FileOutputStream output = new FileOutputStream(file)) { output.getChannel().transferFrom(input, 0, Long.MAX_VALUE); GlowServer.logger.info("Downloaded " + library + ' ' + version + '.'); } } catch (IOException e) { GlowServer.logger.log(Level.WARNING, "Failed to download: " + library + ' ' + version, e); file.delete(); return; } } try { Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class); method.setAccessible(true); method.invoke(sysLoader, file.toURI().toURL()); } catch (ReflectiveOperationException | MalformedURLException e) { GlowServer.logger.log(Level.WARNING, "Failed to add to classpath: " + library + " " + version, e); } }
Source:
<code>private MultiMap<Class<?>, AnalyticalTask<?>> determineTasks() { MultiMap<Class<?>, AnalyticalTask<?>> result = MultiMap.create(); context.getParts((Class<AnalyticalTask<?>>) getAnalyticalTaskType()).forEach(task -> { <START> if (isMatchingEntityType(task)) { <END> result.put(task.getType(), task); } }); return result; }</code><technical_language>stream().filter(this::isMatchingEntityType).forEach(result.put)</technical_language>

Target:
private MultiMap<Class<?>, AnalyticalTask<?>> determineTasks() { MultiMap<Class<?>, AnalyticalTask<?>> result = MultiMap.create(); context.getParts((Class<AnalyticalTask<?>>) getAnalyticalTaskType()) .stream() .filter(this::isMatchingEntityType) .forEach(task -> result.put(task.getType(), task)); return result; }
Source:
<code>public void expectedInitialParameters() throws Exception { TimeZone.setDefault(tzPlus0800); con = TestUtil.openDB(); Map<String,String> params = ((PGConnection)con).getParameterStatuses(); Assert.assertEquals("UTF8", params.get("client_encoding")); Assert.assertNotNull(params.get("DateStyle")); <START> Assert.assertTrue(params.get("DateStyle").startsWith("ISO")); <END> Assert.assertEquals("GMT-08:00", params.get("TimeZone")); Assert.assertNotNull(params.get("integer_datetimes")); Assert.assertNotNull(params.get("is_superuser")); Assert.assertNotNull(params.get("server_encoding")); Assert.assertNotNull(params.get("server_version")); Assert.assertNotNull(params.get("session_authorization")); Assert.assertNotNull(params.get("standard_conforming_strings")); if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) { Assert.assertNotNull(params.get("IntervalStyle")); } else { Assert.assertNull(params.get("IntervalStyle")); } if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) { Assert.assertEquals("Driver Tests", params.get("application_name")); } else { Assert.assertNull(params.get("application_name")); } Assert.assertNull(params.get("nonexistent")); Assert.assertNull(params.get("enable_hashjoin")); TestUtil.closeDB(con); }</code><technical_language>Please refrain kind of asserts. If fails hard debug. failure like: expected true, false, in fact interested in actual of DateStyle parameter</technical_language>

Target:
public void expectedInitialParameters() throws Exception { TimeZone.setDefault(tzPlus0800); con = TestUtil.openDB(); Map<String,String> params = ((PGConnection)con).getParameterStatuses(); Assert.assertEquals("UTF8", params.get("client_encoding")); Assert.assertNotNull(params.get("DateStyle")); Assert.assertThat(params.get("DateStyle"), StringStartsWith.startsWith("ISO")); Assert.assertEquals("GMT-08:00", params.get("TimeZone")); Assert.assertNotNull(params.get("integer_datetimes")); Assert.assertNotNull(params.get("is_superuser")); Assert.assertNotNull(params.get("server_encoding")); Assert.assertNotNull(params.get("server_version")); Assert.assertNotNull(params.get("session_authorization")); Assert.assertNotNull(params.get("standard_conforming_strings")); if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v8_4)) { Assert.assertNotNull(params.get("IntervalStyle")); } else { Assert.assertNull(params.get("IntervalStyle")); } if (TestUtil.haveMinimumServerVersion(con, ServerVersion.v9_0)) { Assert.assertEquals("Driver Tests", params.get("application_name")); } else { Assert.assertNull(params.get("application_name")); } Assert.assertNull(params.get("nonexistent")); Assert.assertNull(params.get("enable_hashjoin")); TestUtil.closeDB(con); }
Source:
<code>public void testObjectMovedWithinPack() throws IncorrectObjectTypeException, IOException { final Repository eden = createBareRepository(); final RevObject o1 = writeBlob(eden, "o1"); final File[] out1 = pack(eden, o1); assertEquals(o1.name(), parse(o1).name()); whackCache(); final RevObject o2 = writeBlob(eden, "o2"); <START> try (final PackWriter pw = new PackWriter(eden)) { <END> pw.addObject(o2); pw.addObject(o1); write(out1, pw); } assertEquals(o1.name(), parse(o1).name()); assertEquals(o2.name(), parse(o2).name()); }</code><technical_language>(optional)</technical_language>

Target:
public void testObjectMovedWithinPack() throws IncorrectObjectTypeException, IOException { final Repository eden = createBareRepository(); final RevObject o1 = writeBlob(eden, "o1"); final File[] out1 = pack(eden, o1); assertEquals(o1.name(), parse(o1).name()); whackCache(); final RevObject o2 = writeBlob(eden, "o2"); try (PackWriter pw = new PackWriter(eden)) { pw.addObject(o2); pw.addObject(o1); write(out1, pw); } assertEquals(o1.name(), parse(o1).name()); assertEquals(o2.name(), parse(o2).name()); }
Source:
<code>public Map<TaskId, Long> getTaskOffsetSums() { final Map<TaskId, Long> taskOffsetSums = new HashMap<>(); final File[] stateDirs = stateDirectory.listTaskDirectories(); if (stateDirs != null) { for (final File dir : stateDirs) { try { final TaskId id = TaskId.parse(dir.getName()); final Task task = tasks.get(id); if (task != null) { if (task.isActive() && task.state() == RUNNING) { taskOffsetSums.put(id, Task.LATEST_OFFSET); } else { taskOffsetSums.put(id, computeOffsetSum(task.changelogOffsets())); } } else { try { <START> final File checkpointFile = new File(dir, StateManagerUtil.CHECKPOINT_FILE_NAME); if (stateDirectory.lock(id) && checkpointFile.exists()) { <END> taskOffsetSums.put(id, computeOffsetSum(new OffsetCheckpoint(checkpointFile).read())); lockedUnassignedTaskDirectories.add(id); } } catch (final IOException e) { } } } catch (final TaskIdFormatException e) { } } } return taskOffsetSums; }</code><technical_language>get lock first, check if checkpoint file exists</technical_language>

Target:
public Map<TaskId, Long> getTaskOffsetSums() { final Map<TaskId, Long> taskOffsetSums = new HashMap<>(); for (final TaskId id : lockedTaskDirectories) { final Task task = tasks.get(id); if (task != null) { if (task.isActive() && task.state() == RUNNING) { taskOffsetSums.put(id, Task.LATEST_OFFSET); } else { taskOffsetSums.put(id, sumOfChangelogOffsets(id, task.changelogOffsets())); } } else { final File checkpointFile = stateDirectory.checkpointFileFor(id); try { if (checkpointFile.exists()) { taskOffsetSums.put(id, sumOfChangelogOffsets(id, new OffsetCheckpoint(checkpointFile).read())); } } catch (final IOException e) { log.warn(String.format("Exception caught while trying to read checkpoint for task %s:", id), e); } } } return taskOffsetSums; }
Source:
<code>private void saveCommonStorageProperties(StorageModel model) { <START> storageDomain.setStorageName(model.getName().getEntity()); <END> saveDefaultedStorageProperties(model, storageDomain); }</code><technical_language>This is done line 816. Do need here</technical_language>

Target:
private void saveCommonStorageProperties(StorageModel model) { saveDefaultedStorageProperties(model, storageDomain); }
Source:
<code>public void massClearNetworkFromNics(List<Guid> nicIds) { getCallsHandler().executeStoredProcAsBatch("Clear_network_from_nics", nicIds, new <START> MapSqlParameterMapper<Guid>() <END> { @Override public MapSqlParameterSource map(Guid id) { CustomMapSqlParameterSource paramSource = getCustomMapSqlParameterSource(); paramSource.addValue("id", id); return paramSource; } }); }</code><technical_language>convention is mappers singletons</technical_language>

Target:
public void massClearNetworkFromNics(List<Guid> nicIds) { getCallsHandler().executeStoredProcAsBatch("Clear_network_from_nics", nicIds, getIdParameterMapper()); }
Source:
<code>public void associateAsyncPrettyPrinterWithId( String requestId, AsyncPrettyPrinter asyncPrettyPrinter) { <START> if (mRequestIdMap.containsKey(requestId)) { <END> throw new IllegalArgumentException("cannot associate different " + "pretty printers with the same request id: "+requestId); } mRequestIdMap.put(requestId, asyncPrettyPrinter); }</code><technical_language>This is appropriately thread safe. require synchronization atomic operations performed lock. In this case, for threads race associating async pretty printer request id report key attempt add it. This is solved in of ways here: a) a locking object synchronize for entire method body b) advantage of fact put returns if present throw if returns non-null</technical_language>

Target:
public void associateAsyncPrettyPrinterWithId( String requestId, AsyncPrettyPrinter asyncPrettyPrinter) { if (mRequestIdMap.put(requestId, asyncPrettyPrinter) != null) { throw new IllegalArgumentException("cannot associate different " + "pretty printers with the same request id: "+requestId); } }
Source:
<code>private int calculateLegendHeight() { <START> return simplePlot.getOffsetHeight() - 28; <END> }</code><technical_language>constant for axis label heigth</technical_language>

Target:
private int calculateLegendHeight() { return simplePlot.getOffsetHeight() - X_AXIS_LABEL_HEIGHT - 2 * TOTAL_BORDERS_WIDTH; }
Source:
<code>public static String getMimeTypeFromUrl(String url) { <START> if (url != null) { <END> String extension = FilenameUtils.getExtension(url); if (extension != null) { return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); } } return null; }</code><technical_language>I change this if(url == null) { return null; } indentation, code a lot cleaner</technical_language>

Target:
public static String getMimeTypeFromUrl(String url) { if (url == null) { return null; } String extension = FilenameUtils.getExtension(url); if (extension == null) { return null; } return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension); }
Source:
<code>public void conditional_expression_in_lambda() { Result result = Result.createFor("ConditionalExpressionInLambda"); JavaSymbol foo = result.symbol("foo"); <START> assertThat(foo.usages()).hasSize(1); <END> }</code><technical_language>Please a direct test : this is indirect. test expected type of conditional expression</technical_language>

Target:
public void conditional_expression_in_lambda() { Result result = Result.createFor("ConditionalExpressionInLambda"); JavaSymbol foo = result.symbol("foo"); assertThat(foo.usages()).hasSize(1); IdentifierTree map = result.referenceTree(8, 8); MethodJavaType mapJavaType = (MethodJavaType) map.symbolType(); assertThat(mapJavaType.resultType.isTagged(JavaType.DEFERRED)).isTrue(); JavaType lambdaType = (JavaType) ((MethodInvocationTree) map.parent().parent()).arguments().get(0).symbolType(); assertThat(lambdaType.isParameterized()).isTrue(); assertThat(lambdaType.is("java.util.function.Function")).isTrue(); JavaType returnType = ((ParametrizedTypeJavaType) lambdaType).typeSubstitution.substitutedTypes().get(1); assertThat(returnType.isSubtypeOf("java.lang.Comparable")).isTrue(); JavaSymbol bar = result.symbol("bar"); assertThat(bar.usages()).hasSize(1); IdentifierTree flatMap = result.referenceTree(13, 8); MethodJavaType flatMapJavaType = (MethodJavaType) flatMap.symbolType(); assertThat(flatMapJavaType.resultType.isTagged(JavaType.DEFERRED)).isTrue(); lambdaType = (JavaType) ((MethodInvocationTree) flatMap.parent().parent()).arguments().get(0).symbolType(); assertThat(lambdaType.isParameterized()).isTrue(); assertThat(lambdaType.is("java.util.function.Function")).isTrue(); returnType = ((ParametrizedTypeJavaType) lambdaType).typeSubstitution.substitutedTypes().get(1); assertThat(returnType.isParameterized()).isTrue(); assertThat(returnType.is("java.util.stream.Stream")).isTrue(); JavaType substitution = ((ParametrizedTypeJavaType) returnType).typeSubstitution.substitutedTypes().get(0); assertThat(substitution.is("java.lang.Integer")).isTrue(); }
Source:
<code>protected ChannelHandler findHttpResponseDecoderToReplace(ChannelPipeline pipeline) throws IllegalStateException { if (httpResponseDecoderName != null) { final ChannelHandler decoder = pipeline.get(httpResponseDecoderName); if (decoder == null) { throw new IllegalStateException("No http response decoder found with name \"" + httpResponseDecoderName + "\""); <START> } else if (!(decoder instanceof HttpResponseDecoder || decoder instanceof HttpClientCodec)) { <END> throw new IllegalStateException("Expected decoder with name \"" + httpResponseDecoderName + "\" to be a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName() + " but found " + decoder.getClass().getCanonicalName()); } return decoder; } ChannelHandler decoder = pipeline.get(HttpResponseDecoder.class); if (decoder == null) { decoder = pipeline.get(HttpClientCodec.class); if (decoder == null) { throw new IllegalStateException("ChannelPipeline does not contain " + "a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName()); } } return decoder; }</code><technical_language>nit: remove else throw in if</technical_language>

Target:
protected ChannelHandler findHttpResponseDecoderToReplace(ChannelPipeline pipeline) throws IllegalStateException { if (httpResponseDecoderName != null) { final ChannelHandler decoder = pipeline.get(httpResponseDecoderName); if (decoder == null) { throw new IllegalStateException("No http response decoder found with name \"" + httpResponseDecoderName + "\""); } if (!(decoder instanceof HttpResponseDecoder || decoder instanceof HttpClientCodec)) { throw new IllegalStateException("Expected decoder with name \"" + httpResponseDecoderName + "\" to be a " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName() + " but found " + decoder.getClass().getCanonicalName()); } return decoder; } ChannelHandler decoder = pipeline.get(HttpResponseDecoder.class); if (decoder == null) { decoder = pipeline.get(HttpClientCodec.class); if (decoder == null) { throw new IllegalStateException("ChannelPipeline does not contain " + "an " + HttpResponseDecoder.class.getSimpleName() + " or " + HttpClientCodec.class.getSimpleName()); } } return decoder; }
Source:
<code>Map<String, String> getSeverityReasonAttributes() { <START> return severityReasonAttributes; <END> }</code><technical_language>want consider wrapping this Collections.unmodifiableMap() clear this field mutated</technical_language>

Target:
Map<String, String> getSeverityReasonAttributes() { return Collections.unmodifiableMap(severityReasonAttributes); }
Source:
<code>private boolean validPayload(final SessionWrapper session, final Payload payload) { final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); <START> if ( null != verifier ) { <END> return verifier.verified(payload, session); } return true; }</code><technical_language>I change this for a return (null != verifier)? verifier.verified(payload, session): true;</technical_language>

Target:
private boolean validPayload(final SessionWrapper session, final Payload payload) { final PayloadVerifier verifier = this.payloadVerifierFactory.getVerifier(payload); return (null != verifier) ? verifier.verified(payload, session) : true; }
Source:
<code>public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; <START> return em.createNativeQuery(qstr, Object[].class).getResultList(); <END> }</code><technical_language>this default return type</technical_language>

Target:
public List<Object[]> getDvObjectInfoForMyData(List<Long> dvObjectIdList){ String dvObjectClause = getDvObjectIdListClause(dvObjectIdList); if (dvObjectClause==null){ return null; } String qstr = "SELECT dv.id, dv.dtype, dv.owner_id"; qstr += " FROM dvobject dv"; qstr += " WHERE dv.id IN " + dvObjectClause; qstr += ";"; return em.createNativeQuery(qstr).getResultList(); }
Source:
<code>private static List<VmDevice> getPluggedInterfaces(List<VmDevice> devices) { <START> ArrayList<VmDevice> result = new ArrayList<VmDevice>(); <END> for (VmDevice device : devices) { if (isBridge(device) && device.getIsPlugged()) { result.add(device); } } return result; }</code><technical_language>reference type List</technical_language>

Target:
private static List<VmDevice> getPluggedInterfaces(List<VmDevice> devices) { List<VmDevice> result = new ArrayList<VmDevice>(); for (VmDevice device : devices) { if (isBridge(device) && device.getIsPlugged()) { result.add(device); } } return result; }
Source:
<code>private String writeToCSV(SortedMap<Long, List<CircuitStatistics>> circuitStatistics) throws IOException { StringBuilder sb = new StringBuilder(); CSVWriter writer = new CSVWriter(new StringBuilderWriter(sb), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); try { for (Long timestamp : circuitStatistics.keySet()) for (CircuitStatistics currentStatistic : circuitStatistics.get(timestamp)) { String[] csvStatistic = new String[7]; csvStatistic[0] = String.valueOf(timestamp); csvStatistic[1] = String.valueOf(currentStatistic.getSlaFlowId()); csvStatistic[2] = String.valueOf(currentStatistic.getThroughput()); csvStatistic[3] = String.valueOf(currentStatistic.getPacketLoss()); csvStatistic[4] = String.valueOf(currentStatistic.getDelay()); csvStatistic[5] = String.valueOf(currentStatistic.getJitter()); <START> csvStatistic[6] = String.valueOf(currentStatistic.getFlowData()); <END> writer.writeNext(csvStatistic); } return sb.toString(); } finally { writer.close(); } }</code><technical_language>currentStatistics fields of type String. String.valueOf() is unnecessary (but in timestamp :P)</technical_language>

Target:
private String writeToCSV(SortedMap<Long, List<CircuitStatistics>> circuitStatistics) throws IOException { StringBuilder sb = new StringBuilder(); CSVWriter writer = new CSVWriter(new StringBuilderWriter(sb), CSVWriter.DEFAULT_SEPARATOR, CSVWriter.NO_QUOTE_CHARACTER); try { for (Long timestamp : circuitStatistics.keySet()) for (CircuitStatistics currentStatistic : circuitStatistics.get(timestamp)) { String[] csvStatistic = new String[7]; csvStatistic[0] = String.valueOf(timestamp); csvStatistic[1] = currentStatistic.getSlaFlowId(); csvStatistic[2] = currentStatistic.getThroughput(); csvStatistic[3] = currentStatistic.getPacketLoss(); csvStatistic[4] = currentStatistic.getDelay(); csvStatistic[5] = currentStatistic.getJitter(); csvStatistic[6] = currentStatistic.getFlowData(); writer.writeNext(csvStatistic); } return sb.toString(); } finally { writer.close(); } }
Source:
<code>public Serializable next() { if (!this.hasNext()) { throw new NoSuchElementException(); } AttributeDescriptor attributeDescriptor = this.attributeDescriptorList.get(index); Attribute attribute = metacard.getAttribute(attributeDescriptor.getName()); index++; if (attribute != null) { if (attributeDescriptor.isMultiValued()) { StringBuilder valuesBuilder = new StringBuilder(); List<Serializable> values = attribute.getValues(); for (int i = 0; i < values.size(); i++) { if (i > 0) { valuesBuilder.append(MULTIVALUE_DELIMITER); } valuesBuilder.append(values.get(i)); } <START> return valuesBuilder.toString(); <END> } else { return attribute.getValue(); } } return ""; }</code><technical_language>replace this block (lines [70..79]) return StringUtils.join(attribute.getValues(), MULTIVALUE_DELIMITER)</technical_language>

Target:
public Serializable next() { if (!this.hasNext()) { throw new NoSuchElementException(); } AttributeDescriptor attributeDescriptor = this.attributeDescriptorList.get(index); Attribute attribute = metacard.getAttribute(attributeDescriptor.getName()); index++; if (attribute != null) { if (attributeDescriptor.isMultiValued()) { return StringUtils.join(attribute.getValues(), MULTIVALUE_DELIMITER); } else { return attribute.getValue(); } } return ""; }
Source:
<code>public void testAddRemoveAdd_fromSameWorkSource() { WorkSource ws1 = null; WorkSource ws2 = new WorkSource(50, "foo"); <START> ws1 = ws2; <END> ws1.add(ws2); assertTrue(ws1.remove(ws2)); ws1.add(ws2); assertEquals(0, ws1.size()); }</code><technical_language>This confused a bit, I initially thought bug triggered reference equality that. I clearer users, if WorkSource ws1 = new WorkSource(50, "foo"); WorkSource ws2 = new WorkSource(50, "foo"); removed this line instead</technical_language>

Target:
public void testAddRemoveAdd_fromSameWorkSource() { WorkSource ws = new WorkSource(50, "foo"); ws.add(ws); assertEquals(1, ws.size()); assertTrue(ws.remove(ws)); assertEquals(0, ws.size()); ws.add(ws); assertEquals(0, ws.size()); }
Source:
<code>private void removeEmptyGroupAfterTimeout(MessageGroup messageGroup, long timeout) { Object groupId = messageGroup.getGroupId(); UUID groupUuid = UUIDConverter.getUUID(groupId); ScheduledFuture<?> scheduledFuture = getTaskScheduler() .schedule(() -> { Lock lock = this.lockRegistry.obtain(groupUuid.toString()); try { lock.lockInterruptibly(); try { this.messageStore.removeMessageGroup(groupId); } finally { lock.unlock(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); <START> this.logger.debug("Thread was interrupted while trying to obtain lock"); <END> } }, new Date(System.currentTimeMillis() + timeout)); if (this.logger.isDebugEnabled()) { this.logger.debug("Schedule empty MessageGroup [ " + groupId + "] for removal."); } this.expireGroupScheduledFutures.put(groupUuid, scheduledFuture); }</code><technical_language>Reschedule</technical_language>

Target:
private void removeEmptyGroupAfterTimeout(MessageGroup messageGroup, long timeout) { Object groupId = messageGroup.getGroupId(); UUID groupUuid = UUIDConverter.getUUID(groupId); ScheduledFuture<?> scheduledFuture = getTaskScheduler() .schedule(() -> { Lock lock = this.lockRegistry.obtain(groupUuid.toString()); try { lock.lockInterruptibly(); try { this.expireGroupScheduledFutures.remove(groupUuid); MessageGroup groupNow = this.messageStore.getMessageGroup(groupUuid); boolean removeGroup = groupNow.size() == 0 && groupNow.getLastModified() <= (System.currentTimeMillis() - this.minimumTimeoutForEmptyGroups); if (removeGroup) { if (this.logger.isDebugEnabled()) { this.logger.debug("Removing empty group: " + groupUuid); } this.messageStore.removeMessageGroup(groupId); } } finally { lock.unlock(); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); if (this.logger.isDebugEnabled()) { this.logger.debug("Thread was interrupted while trying to obtain lock." + "Rescheduling empty MessageGroup [ " + groupId + "] for removal."); } removeEmptyGroupAfterTimeout(messageGroup, timeout); } }, new Date(System.currentTimeMillis() + timeout)); if (this.logger.isDebugEnabled()) { this.logger.debug("Schedule empty MessageGroup [ " + groupId + "] for removal."); } this.expireGroupScheduledFutures.put(groupUuid, scheduledFuture); }
Source:
<code>public String toString() { <START> return "profile (" + authz + ")"; END> }</code><technical_language>"profile" part of quotes</technical_language>

Target:
public String toString() { return profile + " (" + authz + ")"; }
Source:
<code>public void third_party_symbols() { <START> Map<String, Symbol> emojiSymbols = TypeShed.typeShedSymbols("emoji").stream().collect(Collectors.toMap(Symbol::name, Function.identity())); <END> Symbol emojizeSymbol = emojiSymbols.get("emojize"); assertThat(emojizeSymbol.kind()).isEqualTo(Kind.FUNCTION); assertThat(((FunctionSymbolImpl) emojizeSymbol).declaredReturnType().canOnlyBe("str")).isTrue(); assertThat(TypeShed.standardLibrarySymbol("emoji", "emoji.emojize")).isSameAs(emojizeSymbol); }</code><technical_language>discussed if I run this test in isolation I get a NPE</technical_language>

Target:
public void third_party_symbols() { Map<String, Symbol> emojiSymbols = TypeShed.typeShedSymbolsForModule("emoji").stream().collect(Collectors.toMap(Symbol::name, Function.identity())); Symbol emojizeSymbol = emojiSymbols.get("emojize"); assertThat(emojizeSymbol.kind()).isEqualTo(Kind.FUNCTION); assertThat(((FunctionSymbolImpl) emojizeSymbol).declaredReturnType().canOnlyBe("str")).isTrue(); assertThat(TypeShed.standardLibrarySymbol("emoji", "emoji.emojize")).isSameAs(emojizeSymbol); }
Source:
<code>private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, <START> String emptyValue, int maxCharsPerColumn, boolean ignoreTrailingAndLeadingWhitespace) { <END> CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); Preconditions.condition(maxCharsPerColumn > 0, () -> "maxCharsPerColumn must be a positive number: " + maxCharsPerColumn); settings.setMaxCharsPerColumn(maxCharsPerColumn); return settings; }</code><technical_language>forgot pass ignoreTrailingAndLeadingWhitespace CsvParserSettings</technical_language>

Target:
private static CsvParserSettings createParserSettings(String delimiter, String lineSeparator, char quote, String emptyValue, int maxCharsPerColumn, boolean ignoreTrailingAndLeadingWhitespace) { CsvParserSettings settings = new CsvParserSettings(); settings.getFormat().setDelimiter(delimiter); settings.getFormat().setLineSeparator(lineSeparator); settings.getFormat().setQuote(quote); settings.getFormat().setQuoteEscape(quote); settings.setEmptyValue(emptyValue); settings.setAutoConfigurationEnabled(false); settings.setIgnoreLeadingWhitespaces(ignoreTrailingAndLeadingWhitespace); settings.setIgnoreTrailingWhitespaces(ignoreTrailingAndLeadingWhitespace); Preconditions.condition(maxCharsPerColumn > 0, () -> "maxCharsPerColumn must be a positive number: " + maxCharsPerColumn); settings.setMaxCharsPerColumn(maxCharsPerColumn); return settings; }
Source:
<code>private Observable<List<Server>> refreshServerCache() { return serverSource .compose(ChangeNotifications.<Server>buffers()) .compose(ChangeNotifications.<Server>snapshots()) <START> .materialize() <END> .concatMap(new Func1<Notification<LinkedHashSet<Server>>, Observable<? extends List<Server>>>() { @Override public Observable<? extends List<Server>> call(Notification<LinkedHashSet<Server>> rxNotification) { switch (rxNotification.getKind()) { case OnNext: LinkedHashSet<Server> servers = rxNotification.getValue(); if (servers.isEmpty()) { return Observable.never(); } else { logger.info("Populating the serverCache with servers", servers.size()); List<Server> newServerCache = new ArrayList<>(servers); Collections.sort(newServerCache); serverCacheRef.set(newServerCache); } break; case OnCompleted: break; case OnError: return Observable.error(rxNotification.getThrowable()); } return Observable.just(serverCacheRef.get()); } }) .timeout(warmUpTimeout, timeUnit) .onErrorResumeNext(new Func1<Throwable, Observable<? extends List<Server>>>() { @Override public Observable<? extends List<Server>> call(Throwable throwable) { if (!(throwable instanceof TimeoutException)) { logger.warn("Exception thrown when connecting the serverCache to the serverSource, using backup values", throwable); } return Observable.just(serverCacheRef.get()); } }) .take(1); }</code><technical_language>refactorings in ChangeNotifications allow for empty server lists. I in beginning emit empty list (filter empty lists out), allow afterwards, means previously advertised server away. bottom line is ChangeNotifications transformers offer enough flexibility do that</technical_language>

Target:
private Observable<List<Server>> refreshServerCache() { return serverSource .compose(ChangeNotifications.<Server>buffers()) .compose(ChangeNotifications.<Server>snapshots()) .materialize() .concatMap(new Func1<Notification<LinkedHashSet<Server>>, Observable<? extends List<Server>>>() { @Override public Observable<? extends List<Server>> call(Notification<LinkedHashSet<Server>> rxNotification) { switch (rxNotification.getKind()) { case OnNext: LinkedHashSet<Server> servers = rxNotification.getValue(); if (servers.isEmpty()) { return Observable.never(); } else { logger.info("Populating the serverCache with servers", servers.size()); List<Server> newServerCache = new ArrayList<>(servers); Collections.sort(newServerCache); serverCacheRef.set(newServerCache); } break; case OnCompleted: break; case OnError: return Observable.error(rxNotification.getThrowable()); } return Observable.just(serverCacheRef.get()); } }) .timeout(cacheRefreshTimeout, timeUnit) .onErrorResumeNext(new Func1<Throwable, Observable<? extends List<Server>>>() { @Override public Observable<? extends List<Server>> call(Throwable throwable) { if (!(throwable instanceof TimeoutException)) { logger.warn("Exception thrown when connecting the serverCache to the serverSource, using backup values", throwable); } return Observable.just(serverCacheRef.get()); } }) .take(1); }
Source:
<code>private static String getResponseBody(String path) throws IOException { return ByteSources .asByteSource(GlacierClientMockTest.class.getResourceAsStream(path)) .asCharSource(UTF_8) <START> .read(); <END> }</code><technical_language>write this more succinctly as: Resources.toString(Resources.getResource(getClass(), path), UTF_8));</technical_language>

Target:
private static String getResponseBody(String path) throws IOException { return Resources.toString(Resources.getResource(GlacierClientMockTest.class, path), UTF_8); }
Source:
<code>public void setValue(float val) { <START> if(val < 0f) { <END> value = 0; return; } else if (val > 1f) { value = 1.0f; return; } value = val; }</code><technical_language>Dito Math.min()/Math.max()</technical_language>

Target:
public void setValue(float val) { value = SolMath.clamp(val); }
Source:
<code>public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException { try { <START> Method newBuilder = newBuilderMethodCache.get(type); <END> if (newBuilder == null) { newBuilder = type.getMethod("newBuilder"); } final Message.Builder builder = (Message.Builder) newBuilder .invoke(type); return builder.mergeFrom(entityStream).build(); } catch (Exception e) { throw new WebApplicationException(e); } }</code><technical_language>is adding items cache</technical_language>

Target:
public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException { try { Method newBuilder = newBuilderMethodCache.get(type); if (newBuilder == null) { newBuilder = type.getMethod("newBuilder"); newBuilderMethodCache.put(type, newBuilder); } final Message.Builder builder = (Message.Builder) newBuilder .invoke(type); return builder.mergeFrom(entityStream).build(); } catch (Exception e) { throw new WebApplicationException(e); } }
Source:
<code>public static void initializeCarbonContext() { <START> if (System.getProperty("carbon.home") == null) { <END> File file = new File("src/test/resources"); if (file.exists()) { System.setProperty(CARBON_HOME, file.getAbsolutePath()); } } PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); }</code><technical_language>please "CARBON_HOME" variable</technical_language>

Target:
public static void initializeCarbonContext() { if (System.getProperty(CARBON_HOME) == null) { File file = new File("src/test/resources"); if (file.exists()) { System.setProperty(CARBON_HOME, file.getAbsolutePath()); } } PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantDomain( org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_DOMAIN_NAME); PrivilegedCarbonContext.getThreadLocalCarbonContext().setTenantId( org.wso2.carbon.base.MultitenantConstants.SUPER_TENANT_ID); }
Source:
<code>private String getParameterValue(RestRequest restRequest, String name) { List<String> values = restRequest.parameters().get(name); if (values == null) return null; <START> return values.iterator().next(); <END> }</code><technical_language>return values == null ? null : values.iterator().next();</technical_language>

Target:
private String getParameterValue(RestRequest restRequest, String name) { List<String> values = restRequest.parameters().get(name); return values == null ? null : values.iterator().next(); }
Source:
<code>public void missingGrandparentSuperclass() { JavaFileObject javaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", <START> "class Parent extends Missing {}", <END> "", "class TestClass extends Parent {}"); assertAbout(javaSource()) .that(javaFileObject) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); }</code><technical_language>multiple classes here? stays Google's Java style</technical_language>

Target:
public void missingGrandparentSuperclass() { JavaFileObject parentJavaFileObject = JavaFileObjects.forSourceLines( "test.Parent", "package test;", "", "class Parent extends Missing {}"); JavaFileObject testClassJavaFileObject = JavaFileObjects.forSourceLines( "test.TestClass", "package test;", "", "class TestClass extends Parent {}"); assertAbout(javaSources()) .that(ImmutableList.of(parentJavaFileObject, testClassJavaFileObject)) .processedWith(new AssertingProcessor() { @Override void runAssertions() { TypeElement testClassElement = processingEnv.getElementUtils().getTypeElement("test.TestClass"); assertThat(SuperficialValidation.validateElement(testClassElement)).isFalse(); } }) .failsToCompile(); }
Source:
<code>public void TestParserMoreFieldsOnlyPOJOPortConnected() { parser.parsedOutput.setSink(null); parser.beginWindow(0); parser.in.process( "1234,98233,adxyz,0.2,2015-03-08 03:37:12,11/12/2012,12,y,OPTIMIZATION,CAMP_AD,Y,yes,ExtraField".getBytes()); parser.endWindow(); Assert.assertEquals(0, objectPort.collectedTuples.size()); Assert.assertEquals(0, pojoPort.collectedTuples.size()); <START> Assert.assertEquals(1, error.collectedTuples.size()); <END> }</code><technical_language>add small addition error port string tuple passed input port</technical_language>

Target:
public void TestParserMoreFieldsOnlyPOJOPortConnected() { String input = "1234,98233,adxyz,0.2,2015-03-08 03:37:12,11/12/2012,12,y,OPTIMIZATION,CAMP_AD,Y,yes,ExtraField"; parser.parsedOutput.setSink(null); parser.beginWindow(0); parser.in.process(input.getBytes()); parser.endWindow(); Assert.assertEquals(0, objectPort.collectedTuples.size()); Assert.assertEquals(0, pojoPort.collectedTuples.size()); Assert.assertEquals(1, error.collectedTuples.size()); KeyValPair<String, String> errorTuple = (KeyValPair<String, String>)error.collectedTuples.get(0); Assert.assertEquals(input, errorTuple.getKey()); }
Source:
<code>void deleteServiceIntegrationSecrets( final String serviceKey, final String siteId, final User user) throws DotSecurityException, DotDataException { final Optional<ServiceDescriptor> serviceDescriptorOptional = serviceIntegrationAPI .getServiceDescriptor(serviceKey, user); if (!serviceDescriptorOptional.isPresent()) { <START> throw new DotDataException( <END> String.format(" Couldn't find a descriptor under key `%s` for host `%s` ", serviceKey, siteId)); } final Host host = hostAPI.find(siteId, user, false); if (null == host) { throw new DotDataException( String.format(" Couldn't find any site with identifier `%s` ", siteId)); } serviceIntegrationAPI.deleteSecrets(serviceKey, host, user); }</code><technical_language>NotFoundInDbException similar get 404</technical_language>

Target:
void deleteServiceIntegrationSecrets( final String serviceKey, final String siteId, final User user) throws DotSecurityException, DotDataException { final Optional<ServiceDescriptor> serviceDescriptorOptional = serviceIntegrationAPI .getServiceDescriptor(serviceKey, user); if (!serviceDescriptorOptional.isPresent()) { throw new DoesNotExistException( String.format(" Couldn't find a descriptor under key `%s` for host `%s` ", serviceKey, siteId)); } final Host host = hostAPI.find(siteId, user, false); if (null == host) { throw new DotDataException( String.format(" Couldn't find any site with identifier `%s` ", siteId)); } serviceIntegrationAPI.deleteSecrets(serviceKey, host, user); }
Source:
<code><START> private void printer() { <END> long threadId = Thread.currentThread().getId(); long time = System.currentTimeMillis(); int hashCode = hashCode(); InvocationTracker tracker = new InvocationTracker(time, threadId, hashCode); MyFactory.tracker.add(tracker); }</code><technical_language>static</technical_language>

Target:
private void printer() { long threadId = Thread.currentThread().getId(); long time = System.currentTimeMillis(); int hashCode = hashCode(); InvocationTracker tracker = new InvocationTracker(time, threadId, hashCode); MyFactory.TRACKER.add(tracker); }
Source:
<code>public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { Handle h = db.openHandle(); try { h.inTransaction((handle, status) -> { throw new IllegalArgumentException(); }); } catch (JdbiException e) { fail("Should have thrown a straight RuntimeException"); } catch (IllegalArgumentException e) { <START> assertThat(e).isNotNull(); <END> } catch (Exception e) { fail("Should have been caught at IllegalArgumentException"); } }</code><technical_language>Redundant assertion</technical_language>

Target:
public void testThrowingRuntimeExceptionPercolatesOriginal() throws Exception { db.openHandle().inTransaction((handle, status) -> { throw new IllegalArgumentException(); }); }