auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private String parseParams(ParameterSet params, JSONObject obj) throws Exception { <START> if (params.size() < 2) { <END> return "@SnapshotDelete expects 2 arguments, received " + params.size(); } String[] paths = null; try { paths = (String[])(ParameterConverter.tryToMakeCompatible( String[].class, params.toArray()[0])); } catch (Exception e) { return e.getMessage(); } if (paths == null || paths.length == 0) { return "No paths supplied"; } for (String path : paths) { if (path == null || path.trim().isEmpty()) { return "A path was null or the empty string"; } } String[] nonces = null; try { nonces = (String[])(ParameterConverter.tryToMakeCompatible( String[].class, params.toArray()[1])); } catch (Exception e) { return e.getMessage(); } if (nonces == null || nonces.length == 0) { return "No nonces supplied"; } for (String nonce : nonces) { if (nonce == null || nonce.trim().isEmpty()) { return "A nonce was null or the empty string"; } } if (paths.length != nonces.length) { return "A path must be provided for every nonce"; } String stype = SnapthotPathType.SNAP_PATH.toString(); if (params.size() > 2) { stype = (String )(ParameterConverter.tryToMakeCompatible( String.class, params.toArray()[2])); } obj.put("subselector", "SNAPSHOTDELETE"); obj.put("interval", false); obj.put("paths", paths); obj.put(SnapshotUtil.JSON_PATH_TYPE, stype); obj.put("nonces", nonces); return null; }</code><technical_language>Message "either 2 3"</technical_language>

Target:
private String parseParams(ParameterSet params, JSONObject obj) throws Exception { if (params.size() < 2) { return "@SnapshotDelete expects 2 or 3 arguments, received " + params.size(); } String[] paths = null; Object paramList[] = params.toArray(); try { paths = (String[])(ParameterConverter.tryToMakeCompatible( String[].class, paramList[0])); } catch (Exception e) { return e.getMessage(); } if (paths == null || paths.length == 0) { return "No paths supplied"; } for (String path : paths) { if (path == null || path.trim().isEmpty()) { return "A path was null or the empty string"; } } String[] nonces = null; try { nonces = (String[])(ParameterConverter.tryToMakeCompatible( String[].class, paramList[1])); } catch (Exception e) { return e.getMessage(); } if (nonces == null || nonces.length == 0) { return "No nonces supplied"; } for (String nonce : nonces) { if (nonce == null || nonce.trim().isEmpty()) { return "A nonce was null or the empty string"; } } if (paths.length != nonces.length) { return "A path must be provided for every nonce"; } String stype = SnapshotPathType.SNAP_PATH.toString(); if (params.size() > 2) { stype = (String )(ParameterConverter.tryToMakeCompatible( String.class, paramList[2])); } obj.put("subselector", "SNAPSHOTDELETE"); obj.put("interval", false); obj.put("paths", paths); obj.put(SnapshotUtil.JSON_PATH_TYPE, stype); obj.put("nonces", nonces); return null; }
Source:
<code>private Double interpretOperatorEqual(Object left, Object right) { if (left instanceof String && right instanceof String) { try { return (Double.valueOf((String) left).compareTo(Double.valueOf((String) right))) == 0 ? 1d : 0; } catch (NumberFormatException numberFormatException) { int compareResult = ((String) left).compareTo((String) right); if (compareResult == 0) { return 1d; } } } if (left instanceof Double && right instanceof String) { try { Double tempLeft = (Double) left; Double tempRight = Double.valueOf((String) right); int compareResult; if (tempLeft == 0 || tempRight == 0) { compareResult = ((Double) Math.abs(tempLeft)).compareTo(Math.abs(tempRight)); } else { compareResult = tempLeft.compareTo(tempRight); } if (compareResult == 0) { return 1d; } } catch (NumberFormatException numberFormatException) { return 0d; } } if (left instanceof String && right instanceof Double) { try { Double tempLeft = Double.parseDouble((String) left); Double tempRight = (Double) right; int compareResult; if (tempLeft == 0 || tempRight == 0) { compareResult = ((Double) Math.abs(tempLeft)).compareTo(Math.abs(tempRight)); } else { compareResult = tempLeft.compareTo(tempRight); <START> } <END> if (compareResult == 0) { return 1d; } } catch (NumberFormatException numberFormatException) { return 0d; } } if (left instanceof Double && right instanceof Double) { return (((Double) left).compareTo((Double) right) == 0) ? 1d : 0d; } return 0d; }</code><technical_language>[DRY](<LINK_0> :wink: (duplicate code) This new code block is above. Please improve</technical_language>

Target:
private Double interpretOperatorEqual(Object left, Object right) { try { Double tempLeft = Double.valueOf(String.valueOf(left)); Double tempRight = Double.valueOf(String.valueOf(right)); int compareResult = getCompareResult(tempLeft, tempRight); if (compareResult == 0) { return 1d; } return 0d; } catch (NumberFormatException numberFormatException) { int compareResult = String.valueOf(left).compareTo(String.valueOf(right)); if (compareResult == 0) { return 1d; } return 0d; } }
Source:
<code><START> public File tryFindHook(Repository repository, final Hook hook) { <END> final File gitDir = repository.getDirectory(); final File[] hookDirCandidates = gitDir.listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isDirectory() && pathname.getName().equals("hooks"); } }); if (hookDirCandidates == null || hookDirCandidates.length < 1) return null; final File[] matchingHooks = hookDirCandidates[0] .listFiles(new FileFilter() { public boolean accept(File pathname) { return pathname.isFile() && pathname.getName().equals(hook.getName()); } }); if (matchingHooks == null || matchingHooks.length < 1) return null; return matchingHooks[0]; }</code><technical_language>spent effort FileFilter listFiles calls I guess I overlooking something. implement this method as: public File findHook(Repository repository, final Hook hook) { File hookf = new File( new File(repository.getDirectory(), "hooks"), hook.getName()); //$NON-NLS-1$ return hookf.isFile() ? hookf : null; }</technical_language>

Target:
public File tryFindHook(Repository repository, final Hook hook) { final File hookFile = new File(new File(repository.getDirectory(), "hooks"), hook.getName()); return hookFile.isFile() ? hookFile : null; }
Source:
<code>public ImageButtonCell(ImageResource image) { <START> super("click"); END> this.imageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(image).getHTML()); }</code><technical_language>please BrowserEvents.CLICK instead of string</technical_language>

Target:
public ImageButtonCell(ImageResource image) { super(BrowserEvents.CLICK); this.imageHtml = SafeHtmlUtils.fromTrustedString(AbstractImagePrototype.create(image).getHTML()); }
Source:
<code>protected void createSelection(Composite container) { Label lblSelect = new Label(container, SWT.NONE); lblSelect.setText("Select " + getTypeString() + ":"); List<String> columnNames = Arrays.asList("Name", "Description"); items = createTable(container, SWT.BORDER | SWT.V_SCROLL | extraListOptions, columnNames); List<String> names; List<String> descriptions; if (includeCurrent) { <START> names = (List<String>) ConfigInfo.names(available); descriptions = (List<String>) ConfigInfo.descriptions(available); } else { names = (List<String>) ConfigInfo.namesWithoutCurrent(available); descriptions = (List<String>) ConfigInfo.descriptionsWithoutCurrent(available); <END> } names.sort(String.CASE_INSENSITIVE_ORDER); setMultipleColumnItems(names, descriptions, compOrConfigNamesWithFlags); Group group = new Group(container, SWT.SHADOW_IN); group.setLayout(new RowLayout(SWT.HORIZONTAL)); Label messageImageLabel = new Label(group, SWT.NONE); messageImageLabel.setImage(JFaceResources. getImage(DLG_IMG_MESSAGE_WARNING)); Label messageLabel = new Label(group, SWT.NONE); messageLabel.setFont(JFaceResources.getDialogFont()); messageLabel.setText("Represents Protected " + getTypeString()); }</code><technical_language>is wrong in API here, need this cast. ConfigInfo.names(...) ConfigInfo.descriptions(...) return List collection if ordered, need do names = new ArrayList(ConfigInfo.names(...)). cast is brittle result in hard-to-trace bugs if API updated. Feel free grab if need chat</technical_language>

Target:
protected void createSelection(Composite container) { Label lblSelect = new Label(container, SWT.NONE); lblSelect.setText("Select " + getTypeString() + ":"); List<String> columnNames = Arrays.asList("Name", "Description"); items = createTable(container, SWT.BORDER | SWT.V_SCROLL | extraListOptions, columnNames); SortedMap<String, String> namesAndDescriptions = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER); if (includeCurrent) { namesAndDescriptions = ConfigInfo.namesAndDescriptions(available); } else { namesAndDescriptions = ConfigInfo.namesAndDescriptionsWithoutCurrent(available); } setMultipleColumnItems(namesAndDescriptions, compOrConfigNamesWithFlags); Boolean hasProtectedConfigs = ConfigInfo.hasProtectedElement(available); if (hasProtectedConfigs) { Group group = new Group(container, SWT.SHADOW_IN); group.setLayout(new RowLayout(SWT.HORIZONTAL)); Label messageImageLabel = new Label(group, SWT.NONE); messageImageLabel.setImage(JFaceResources.getImage(DLG_IMG_MESSAGE_WARNING)); Label messageLabel = new Label(group, SWT.NONE); messageLabel.setFont(JFaceResources.getDialogFont()); messageLabel.setText("Represents Protected " + getTypeString()); } }
Source:
<code>public void prepareRun(BatchJoinerContext context) { if (conf.getNumPartitions() != null) { context.setNumPartitions(conf.getNumPartitions()); <START> } <END> FailureCollector collector = context.getFailureCollector(); init(context.getInputSchemas(), collector); Collection<OutputFieldInfo> outputFieldInfos = createOutputFieldInfos(context.getInputSchemas(), collector); context.record(createFieldOperations(outputFieldInfos, perStageJoinKeys)); }</code><technical_language>this line, call collector.getOrThrowException() stop execution if problems</technical_language>

Target:
public void prepareRun(BatchJoinerContext context) { if (conf.getNumPartitions() != null) { context.setNumPartitions(conf.getNumPartitions()); } FailureCollector collector = context.getFailureCollector(); init(context.getInputSchemas(), collector); collector.getOrThrowException(); Collection<OutputFieldInfo> outputFieldInfos = createOutputFieldInfos(context.getInputSchemas(), collector); collector.getOrThrowException(); context.record(createFieldOperations(outputFieldInfos, perStageJoinKeys)); }
Source:
<code>public <T extends Enum<T>> T getEnum(Class<T> enumClass, String path) { ConfigValue v = find(path, ConfigValueType.STRING); String enumName = (String) v.unwrapped(); try { return Enum.valueOf(enumClass, enumName); } catch (IllegalArgumentException e) { throw new ConfigException.BadValue( v.origin(), path, <START> "The enum class %s has no constant of the name %s".format(enumClass.getSimpleName(), enumName)); <END> } }</code><technical_language>if this listed names helpful for people</technical_language>

Target:
public <T extends Enum<T>> T getEnum(Class<T> enumClass, String path) { ConfigValue v = find(path, ConfigValueType.STRING); return getEnumValue(path, enumClass, v); }
Source:
<code>public void testSessionAttemptStatusKilled() throws Exception { RestSessionAttempt attempt = RestSessionAttempt.builder() .id(Id.of("1")) .index(3) .project(IdAndName.of(Id.of("1"), "p")) .workflow(NameOptionalId.of("w", Optional.of(Id.of("1")))) .sessionId(Id.of("1")) .sessionUuid(UUID.randomUUID()) .sessionTime(OffsetDateTime.now(ZoneId.of("UTC"))) .retryAttemptName(Optional.absent()) <START> .done(false) <END> .success(false) .cancelRequested(true) .params(newConfig()) .createdAt(Instant.now()) .finishedAt(Optional.absent()) .build(); assertThat(attempt.getStatus(), is("killed")); }</code><technical_language>In current implementation, killed is printed out session attempt done...</technical_language>

Target:
public void testSessionAttemptStatusKilled() throws Exception { RestSessionAttempt attempt = RestSessionAttempt.builder() .id(Id.of("1")) .index(3) .project(IdAndName.of(Id.of("1"), "p")) .workflow(NameOptionalId.of("w", Optional.of(Id.of("1")))) .sessionId(Id.of("1")) .sessionUuid(UUID.randomUUID()) .sessionTime(OffsetDateTime.now(ZoneId.of("UTC"))) .retryAttemptName(Optional.absent()) .done(true) .success(false) .cancelRequested(true) .params(newConfig()) .createdAt(Instant.now()) .finishedAt(Optional.absent()) .build(); assertThat(attempt.getStatus(), is("killed")); }
Source:
<code>@Test public void requestThrowingBeforeEnqueueFailsEnqueue() throws IOException, InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { <START> call.request(); <END> } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); final CountDownLatch latch = new CountDownLatch(1); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { } @Override public void onFailure(Call<String> call, Throwable t) { assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!"); assertThat(writeCount.get()).isEqualTo(1); latch.countDown(); } }); assertTrue(latch.await(1, SECONDS)); }</code><technical_language>fail()</technical_language>

Target:
@Test public void requestThrowingBeforeEnqueueFailsEnqueue() throws IOException, InterruptedException { Retrofit retrofit = new Retrofit.Builder() .baseUrl(server.url("/")) .addConverterFactory(new ToStringConverterFactory()) .build(); Service service = retrofit.create(Service.class); server.enqueue(new MockResponse()); final AtomicInteger writeCount = new AtomicInteger(); Object a = new Object() { @Override public String toString() { writeCount.incrementAndGet(); throw new RuntimeException("Broken!"); } }; Call<String> call = service.postRequestBody(a); try { call.request(); fail(); } catch (RuntimeException e) { assertThat(e).hasMessage("Broken!"); } assertThat(writeCount.get()).isEqualTo(1); final CountDownLatch latch = new CountDownLatch(1); call.enqueue(new Callback<String>() { @Override public void onResponse(Call<String> call, Response<String> response) { } @Override public void onFailure(Call<String> call, Throwable t) { assertThat(t).isExactlyInstanceOf(RuntimeException.class).hasMessage("Broken!"); assertThat(writeCount.get()).isEqualTo(1); latch.countDown(); } }); assertTrue(latch.await(1, SECONDS)); }
Source:
<code>protected void onStop() { super.onStop(); Log.d(TAG, "Player Activity Stopped"); <START> if (player != null) { <END> player.suspend(); } }</code><technical_language>null != player, this is a typo safety mechanism</technical_language>

Target:
protected void onStop() { super.onStop(); Log.d(TAG, "Player Activity Stopped"); if (null != player) { player.suspend(); } }
Source:
<code>public void populateSparkWebUrl(InterpreterContext ctx) { sparkUrl = getSparkUIUrl(); Map<String, String> infos = new java.util.HashMap<>(); infos.put("url", sparkUrl); java.lang.Boolean uiEnabled = java.lang.Boolean.parseBoolean( <START> property.getProperty("spark.ui.enabled", "true")); <END> if (!uiEnabled) { infos.put("message", "Spark UI disabled"); } else { if (StringUtils.isNotBlank(sparkUrl)) { infos.put("message", "Spark UI enabled"); } else { infos.put("message", "No spark url defined"); } } if (ctx != null && ctx.getClient() != null) { logger.info("Sending metadata to Zeppelin server: {}", infos.toString()); getZeppelinContext().setEventClient(ctx.getClient()); ctx.getClient().onMetaInfosReceived(infos); } }</code><technical_language>trim <LINK_0> this line? I consistent. ok if trim for other boolean property</technical_language>

Target:
public void populateSparkWebUrl(InterpreterContext ctx) { sparkUrl = getSparkUIUrl(); Map<String, String> infos = new java.util.HashMap<>(); infos.put("url", sparkUrl); String uiEnabledProp = property.getProperty("spark.ui.enabled", "true"); java.lang.Boolean uiEnabled = java.lang.Boolean.parseBoolean( uiEnabledProp.trim()); if (!uiEnabled) { infos.put("message", "Spark UI disabled"); } else { if (StringUtils.isNotBlank(sparkUrl)) { infos.put("message", "Spark UI enabled"); } else { infos.put("message", "No spark url defined"); } } if (ctx != null && ctx.getClient() != null) { logger.info("Sending metadata to Zeppelin server: {}", infos.toString()); getZeppelinContext().setEventClient(ctx.getClient()); ctx.getClient().onMetaInfosReceived(infos); } }
Source:
<code><START> public boolean equals(Object o) { <END> if (o == this) { return true; } else if (o instanceof LinkedHashMultimap) { final LinkedHashMultimap<?, ?> that = (LinkedHashMultimap<?, ?>) o; return this.back.equals(that.back); } else { return false; } }</code><technical_language>same, a one-liner</technical_language>

Target:
public boolean equals(Object o) { if (o == this) { return true; } else if (o instanceof LinkedHashMultimap) { final LinkedHashMultimap<?, ?> that = (LinkedHashMultimap<?, ?>) o; return this.delegate.equals(that.delegate); } else { return false; } }
Source:
<code>GcsController createGcsController(Config configuration, String storageBucket) { final Credential credential; try { credential = createCredentials(configuration); } catch (IOException ioe) { <START> throw new RuntimeException("Unable to create credentials", ioe); <END> } final Storage storage; try { storage = createStorage(credential); } catch (IOException ioe) { throw new RuntimeException("Unable to create google cloud storage client", ioe); } catch (GeneralSecurityException gse) { throw new RuntimeException("Unable to create google cloud storage client", gse); } return GcsController.create(storage, storageBucket); }</code><technical_language>throw original exception wrap in RuntimeException</technical_language>

Target:
GcsController createGcsController(Config configuration, String storageBucket) throws IOException, GeneralSecurityException { final Credential credential = createCredentials(configuration); final Storage storage = createStorage(credential); return GcsController.create(storage, storageBucket); }
Source:
<code>public <T> Binding to(ObservableList<T> dolphinList, Converter<? super T, ? extends S> converter) { boundLists.forEach(addedList -> { <START> if(addedList == list) { <END> throw new UnsupportedOperationException("A JavaFX list can only be bound to one Dolphin Platform list!"); } }); boundLists.add(list); InternalListChangeListener listChangeListener = new InternalListChangeListener(list, converter); Subscription subscription = dolphinList.onChanged(listChangeListener); dolphinList.forEach(item -> list.add(converter.convert(item))); list.clear(); ListChangeListener readOnlyListener = c -> { if (!listChangeListener.isOnChange()) { throw new UnsupportedOperationException("A JavaFX list that is bound to a dolphin list can only be modified by the binding!"); } }; list.addListener(readOnlyListener); return () -> { subscription.unsubscribe(); list.removeListener(readOnlyListener); boundLists.remove(list); }; }</code><technical_language>boundLists a Set</technical_language>

Target:
public <T> Binding to(ObservableList<T> dolphinList, Converter<? super T, ? extends S> converter) { if(boundLists.containsKey(list)) { throw new UnsupportedOperationException("A JavaFX list can only be bound to one Dolphin Platform list!"); }; boundLists.put(list, list); InternalListChangeListener listChangeListener = new InternalListChangeListener(list, converter); Subscription subscription = dolphinList.onChanged(listChangeListener); list.clear(); dolphinList.forEach(item -> list.add(converter.convert(item))); ListChangeListener readOnlyListener = c -> { if (!listChangeListener.isOnChange()) { throw new UnsupportedOperationException("A JavaFX list that is bound to a dolphin list can only be modified by the binding!"); } }; list.addListener(readOnlyListener); return () -> { subscription.unsubscribe(); list.removeListener(readOnlyListener); boundLists.remove(list); }; }
Source:
<code>private T setContentFields(T result, Description inputContent) { result.setCanonicalUri(inputContent.getUri()); result.setCurie(inputContent.getCurie()); Publisher publisher = getPublisher(inputContent.getPublisher()); result.setPublisher(publisher); result.setTitle(inputContent.getTitle()); result.setDescription(inputContent.getDescription()); result.setImage(inputContent.getImage()); result.setThumbnail(inputContent.getThumbnail()); if (inputContent.getSpecialization() != null) { result.setSpecialization(Specialization.fromKey(inputContent.getSpecialization()).valueOrNull()); } if (inputContent.getMediaType() != null) { result.setMediaType(MediaType.valueOf(inputContent.getMediaType().toUpperCase())); } result.setPeople(transformPeople(inputContent.getPeople(), publisher)); result.setEquivalentTo(resolveEquivalences(inputContent.getSameAs())); result.setTopicRefs(topicRefs(inputContent.getTopics())); <START> if (!inputContent.getGenres().isEmpty()) { <END> result.setGenres(inputContent.getGenres()); } return result; }</code><technical_language>Do need guard this setGenres? call if inputContent.getGenres() is empty collection</technical_language>

Target:
private T setContentFields(T result, Description inputContent) { result.setCanonicalUri(inputContent.getUri()); result.setCurie(inputContent.getCurie()); Publisher publisher = getPublisher(inputContent.getPublisher()); result.setPublisher(publisher); result.setTitle(inputContent.getTitle()); result.setDescription(inputContent.getDescription()); result.setImage(inputContent.getImage()); result.setThumbnail(inputContent.getThumbnail()); if (inputContent.getSpecialization() != null) { result.setSpecialization(Specialization.fromKey(inputContent.getSpecialization()).valueOrNull()); } if (inputContent.getMediaType() != null) { result.setMediaType(MediaType.valueOf(inputContent.getMediaType().toUpperCase())); } result.setPeople(transformPeople(inputContent.getPeople(), publisher)); result.setEquivalentTo(resolveEquivalences(inputContent.getSameAs())); result.setTopicRefs(topicRefs(inputContent.getTopics())); result.setGenres(inputContent.getGenres()); return result; }
Source:
<code>private Map<TopicPartition, OffsetAndTimestamp> fetchOffsets() { Map<TopicPartition, OffsetAndTimestamp> storedOffsets; if (ignoreStoredOffsets) { storedOffsets = new HashMap<>(); } else { storedOffsets = kafkaOffsetsRepository.load(firstStartTime); } Map<TopicPartition, Long> topicParts = topicPartitions.stream() .filter(tp -> !storedOffsets.containsKey(tp)) .collect(toMap(o -> o, o -> firstStartTime.toEpochMilli())); if (topicParts.size() > 0) { <START> storedOffsets.putAll(consumer.offsetsForTimes(topicParts)); <END> } return storedOffsets; }</code><technical_language>is this line requires KafkaOffsetsRepository return a mutable map</technical_language>

Target:
private Map<TopicPartition, OffsetAndTimestamp> fetchOffsets() { Map<TopicPartition, OffsetAndTimestamp> storedOffsets; if (ignoreStoredOffsets) { storedOffsets = ImmutableMap.of(); } else { storedOffsets = kafkaOffsetsRepository.load(firstStartTime); } Map<TopicPartition, Long> topicParts = topicPartitions.stream() .filter(tp -> !storedOffsets.containsKey(tp)) .collect(toMap(o -> o, o -> firstStartTime.toEpochMilli())); Map<TopicPartition, OffsetAndTimestamp> results = new HashMap<>(); results.putAll(storedOffsets); if (topicParts.size() > 0) { results.putAll(consumer.offsetsForTimes(topicParts)); } return results; }
Source:
<code>public synchronized void shutdown() { if (this.isShutdown.compareAndSet(false, true)) { <START> closeConnection(); <END> } }</code><technical_language>@overquota #close do #closeConnection #shutdown do #shutdownConnection</technical_language>

Target:
public void shutdown() { close(); }
Source:
<code>public static String desanitizeFromNextUrl(String sanitizedUrl) { return sanitizedUrl.replace("${amp}", "&").replace("${plus}", "%2B").replace("${hash}", "%23") <START> .replace(" ", "+"); <END> }</code><technical_language>For readability, I suggest this line start period in line</technical_language>

Target:
public static String desanitizeFromNextUrl(String sanitizedUrl) { if (sanitizedUrl == null) { return null; } return sanitizedUrl.replace("${amp}", "&") .replace("${plus}", "%2B") .replace("${hash}", "%23") .replace(" ", "+"); }
Source:
<code>public static Field getField(String fieldName, String obfName, Class clazz) { Field field = null; try { field = clazz.getDeclaredField(obfName); } catch (NoSuchFieldException e) { <START> EsteemedInnovation.logger.warn("[EI] Unable to find field " + fieldName + " with its obfuscated " + <END> "name. Trying to find it by its name " + fieldName); try { field = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e1) { e1.printStackTrace(); boolean builderHasAField = false; StringBuilder builder = new StringBuilder(); for (Field field1 : clazz.getDeclaredFields()) { if (builderHasAField) { builder.append(", "); } builder.append(field1.getName()); builderHasAField = true; } EsteemedInnovation.logger.warn("Unable to find " + fieldName + " field in " + clazz.getName() + ".class. Available fields are: " + builder + ". Things are not going to work right."); } } return field; }</code><technical_language>[EI] removed this, [esteemedinnovation] in log entry</technical_language>

Target:
public static Field getField(String fieldName, String obfName, Class clazz) { Field field = null; try { field = clazz.getDeclaredField(obfName); } catch (NoSuchFieldException e) { EsteemedInnovation.logger.warn("Unable to find field " + fieldName + " with its obfuscated " + "name. Trying to find it by its name " + fieldName); try { field = clazz.getDeclaredField(fieldName); } catch (NoSuchFieldException e1) { e1.printStackTrace(); boolean builderHasAField = false; StringBuilder builder = new StringBuilder(); for (Field field1 : clazz.getDeclaredFields()) { if (builderHasAField) { builder.append(", "); } builder.append(field1.getName()); builderHasAField = true; } EsteemedInnovation.logger.warn("Unable to find " + fieldName + " field in " + clazz.getName() + ".class. Available fields are: " + builder + ". Things are not going to work right."); } } return field; }
Source:
<code>private void collectVmPrestartFailureReasons(Map<String, Integer> failureReasons, List<String> messages) { if (log.isInfoEnabled()) { String reason = messages.stream() <START> .filter(str -> { <END> try { return EngineMessage.valueOf(str) != null; } catch(IllegalArgumentException e) { return false; } }) .collect(Collectors.joining(", ")); Integer count = failureReasons.get(reason); failureReasons.put(reason, count == null ? 1 : count + 1); } }</code><technical_language>extract this a separate function? method of EngineMessage</technical_language>

Target:
private void collectVmPrestartFailureReasons(Map<String, Integer> failureReasons, List<String> messages) { if (log.isInfoEnabled()) { String reason = messages.stream() .filter(EngineMessage::contains) .collect(Collectors.joining(", ")); Integer count = failureReasons.get(reason); failureReasons.put(reason, count == null ? 1 : count + 1); } }
Source:
<code>public String generateSelectAllExistingFieldsSql(Connection connection, String namespace) throws SQLException { PreparedStatement statement = connection.prepareStatement( "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?" ); statement.setString(1, namespace); statement.setString(2, name); ResultSet result = statement.executeQuery(); <START> List<Field> exitingFields = new ArrayList<>(); <END> while (result.next()) { String columnName = result.getString(1); for (Field f : fields) { if (f.name.equals(columnName)) { exitingFields.add(f); break; } } } String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; return String.format( "select %s from %s", commaSeparatedNames(exitingFields, fieldPrefix, true), tableName ); }</code><technical_language>spelling error exitingFields</technical_language>

Target:
public String generateSelectAllExistingFieldsSql(Connection connection, String namespace) throws SQLException { PreparedStatement statement = connection.prepareStatement( "SELECT column_name FROM information_schema.columns WHERE table_schema = ? AND table_name = ?" ); statement.setString(1, namespace); statement.setString(2, name); ResultSet result = statement.executeQuery(); List<Field> existingFields = new ArrayList<>(); while (result.next()) { String columnName = result.getString(1); existingFields.add(getFieldForName(columnName)); } String tableName = String.join(".", namespace, name); String fieldPrefix = tableName + "."; return String.format( "select %s from %s", commaSeparatedNames(existingFields, fieldPrefix, true), tableName ); }
Source:
<code>public String exportAsPMML(MLModel model) throws MLPmmlExportException { Externalizable extModel = model.getModel(); try { if (extModel instanceof PMMLModelContainer) { PMMLExportable pmmlExportableModel = ((PMMLModelContainer) extModel).getPMMLExportable(); String pmmlString = pmmlExportableModel.toPMML(); DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); DocumentBuilder builder; try { builder = factory.newDocumentBuilder(); Document document = builder.parse(new InputSource(new StringReader(pmmlString))); Element root = document.getDocumentElement(); root.setAttribute("version", "4.2"); StringWriter stringWriter = new StringWriter(); TransformerFactory tf = TransformerFactory.newInstance(); Transformer transformer = tf.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); <START> } catch (Exception e) { <END> String msg = "Error while appending version attribute to pmml"; log.error(msg, e); throw new MLPmmlExportException(msg); } } else { throw new MLPmmlExportException("PMML export not supported for model type"); } } catch (MLPmmlExportException e) { throw new MLPmmlExportException("PMML export not supported for model type"); } }</code><technical_language>close streams</technical_language>

Target:
public String exportAsPMML(MLModel model) throws MLPmmlExportException { Externalizable extModel = model.getModel(); try { if (extModel instanceof PMMLModelContainer) { PMMLExportable pmmlExportableModel = ((PMMLModelContainer) extModel).getPMMLExportable(); String pmmlString = pmmlExportableModel.toPMML(); try { String pmmlWithVersion = appendVersionToPMML(pmmlString); log.info(pmmlWithVersion); return pmmlWithVersion; } catch (Exception e) { String msg = "Error while appending version attribute to pmml"; log.error(msg, e); throw new MLPmmlExportException(msg); } } else { throw new MLPmmlExportException("PMML export not supported for model type"); } } catch (MLPmmlExportException e) { throw new MLPmmlExportException("PMML export not supported for model type"); } }
Source:
<code>private void setSkipNullPredicate(boolean isReverseScan) { int nextKeyIndex = -1; if (isReverseScan) { if (m_searchkeyExpressions.size() < m_endkeyExpressions.size()) { assert(m_endType == IndexLookupType.LT || m_endType == IndexLookupType.LTE); assert( m_endkeyExpressions.size() - m_searchkeyExpressions.size() == 1); nextKeyIndex = m_searchkeyExpressions.size(); } else { return; } } else { if (m_searchkeyExpressions.size() >= m_endkeyExpressions.size()) { if (m_lookupType == IndexLookupType.GT || m_lookupType == IndexLookupType.GTE) { assert(m_searchkeyExpressions.size() > 0); nextKeyIndex = m_searchkeyExpressions.size() - 1; } } <START> else { <END> return; } } m_skip_null_predicate = IndexScanPlanNode.buildSkipNullPredicate(nextKeyIndex, m_catalogIndex, m_tableScan, m_searchkeyExpressions); if (m_skip_null_predicate != null) { m_skip_null_predicate.resolveForTable((Table)m_catalogIndex.getParent()); } }</code><technical_language>if "m_searchkeyExpressions.size() >= m_endkeyExpressions.size()" is true, "m_lookupType == IndexLookupType.GT || m_lookupType == IndexLookupType.GTE" is false. nextKeyIndex stays -1. In previous version this results in early return. Here, I does. I if this matters, I behavior is subtly different. Adding a return in else clause line 167 fix this</technical_language>

Target:
private void setSkipNullPredicate(boolean isReverseScan) { int nextKeyIndex; if (isReverseScan) { if (m_searchkeyExpressions.size() >= m_endkeyExpressions.size()) { return; } assert(m_endType == IndexLookupType.LT || m_endType == IndexLookupType.LTE); assert(m_endkeyExpressions.size() - m_searchkeyExpressions.size() == 1); nextKeyIndex = m_searchkeyExpressions.size(); } else { if (m_searchkeyExpressions.size() < m_endkeyExpressions.size() || (m_lookupType != IndexLookupType.GT && m_lookupType != IndexLookupType.GTE)) { return; } assert(m_searchkeyExpressions.size() > 0); nextKeyIndex = m_searchkeyExpressions.size() - 1; } m_skip_null_predicate = IndexScanPlanNode.buildSkipNullPredicate( nextKeyIndex, m_catalogIndex, m_tableScan, m_searchkeyExpressions); if (m_skip_null_predicate != null) { m_skip_null_predicate.resolveForTable((Table)m_catalogIndex.getParent()); } }
Source:
<code>private String evaluateDefaultContext(String url) { HttpURLConnection connection = null; try { connection = (HttpURLConnection) new URL(url).openConnection(); connection.setRequestMethod("GET"); connection.setInstanceFollowRedirects(false); connection.getResponseCode(); String location = connection.getHeaderField("Location"); String defaultContext = StringUtils.removeEnd(location, "/sys/info.xhtml"); return StringUtils.isBlank(defaultContext) ? defaultContext : defaultContext + "/"; } catch (IOException ex) { <START> context.log.info("Couldn't evaluate default context of engine > use 'ivy/'"); <END> return "ivy/"; } finally { if (connection != null) { connection.disconnect(); } } }</code><technical_language>unexpected behaviour: prefer a 'warn' log</technical_language>

Target:
private String evaluateDefaultContext(String url) { context.log.debug("Call '" + url + "' to evaluate the default context"); var client = HttpClient.newBuilder().followRedirects(Redirect.NEVER).build(); var request = HttpRequest.newBuilder().uri(URI.create(url)).GET().build(); var result = "ivy/"; try { HttpResponse<String> response = client.send(request, BodyHandlers.ofString()); result = response.headers().firstValue("Location").map(location -> { context.log.debug("'" + url + "' returns location header: " + location); String defaultContext = evaluateIvyContextFromUrl(location); context.log.debug("Evalutate '" + defaultContext + "' as default context"); return defaultContext; }).orElse(result); } catch (IOException | InterruptedException ex) { context.log.warn("Couldn't evaluate default context of engine > use 'ivy/'"); } return result; }
Source:
<code>public List<ExtensionProxy> getExtensionsByService(String provides) { List<ExtensionProxy> results = new ArrayList<>(); for (ExtensionEntry entry : initializedEntries.values()) { <START> if (entry.initialized <END> && entry.extension.getContext().<List> get(Base.ContextKeys.PROVIDES).contains(provides)) { results.add(entry.extension); } } return results; }</code><technical_language>of is initialized if is in initialized entries... now</technical_language>

Target:
public List<ExtensionProxy> getExtensionsByService(String provides) { List<ExtensionProxy> results = new ArrayList<>(); for (ExtensionEntry entry : initializedEntries.values()) { if (entry.extension.getContext().<List> get(Base.ContextKeys.PROVIDES).contains(provides)) { results.add(entry.extension); } } return results; }
Source:
<code>public Map<String, String> highlights( @ApiParam(value = "internal id of the anomaly") @QueryParam("anomalyId") long anomalyId, @Auth ThirdEyePrincipal principal) { Map<String, String> responseMessage = new HashMap<>(); <START> ThirdEyeRcaRestClient rcaClient = new ThirdEyeRcaRestClient(principal, dashboardHost); <END> Map<String, Object> eventHighlights = new HashMap<>(); try { eventHighlights = rcaClient.getRelatedEventHighlights(anomalyId); } catch (IOException e) { LOG.error("Failed to retrieve the RCA Event Highlights", e); } responseMessage.put("relatedEvents", new Gson().toJson(eventHighlights)); Map<String, Object> relatedMetricHighlights = new HashMap<>(); try { relatedMetricHighlights = rcaClient.getRelatedMetricHighlights(anomalyId); } catch (IOException e) { LOG.error("Failed to retrieve the RCA Metric Highlights", e); } responseMessage.put("relatedMetrics", new Gson().toJson(relatedMetricHighlights)); Map<String, Object> cubeHighlights = new HashMap<>(); try { cubeHighlights = rcaClient.getCubeHighlights(anomalyId); } catch (IOException e) { LOG.error("Failed to retrieve the RCA Cube Highlights", e); } responseMessage.put("cubeResults", new Gson().toJson(cubeHighlights)); return responseMessage; }</code><technical_language>thought REST client here. sense REST calls get information modules, for instance RCA info in notification module, consider method call REST calls, this endpoint is RCA calls this method RCA. Method calls give performance error handling</technical_language>

Target:
public Map<String, Object> highlights( @ApiParam(value = "internal id of the anomaly") @QueryParam("anomalyId") long anomalyId, @Auth ThirdEyePrincipal principal) throws Exception { Map<String, Object> responseMessage = new HashMap<>(); MergedAnomalyResultDTO anomalyDTO = DAORegistry.getInstance().getMergedAnomalyResultDAO().findById(anomalyId); Preconditions.checkNotNull(anomalyDTO, "Anomaly doesn't exist in ThirdEye's repository"); String cubeHighlights = this.summaryResource.buildSummary( anomalyDTO.getMetricUrn(), anomalyDTO.getCollection(), anomalyDTO.getMetric(), anomalyDTO.getStartTime(), anomalyDTO.getEndTime(), anomalyDTO.getStartTime() - TimeUnit.DAYS.toMillis(7), anomalyDTO.getEndTime() - TimeUnit.DAYS.toMillis(7), Strings.EMPTY, Strings.EMPTY, DEFAULT_HIGHLIGHT_CUBE_SUMMARY_SIZE, DEFAULT_HIGHLIGHT_CUBE_DEPTH, SummaryResource.DEFAULT_HIERARCHIES, false, DEFAULT_EXCLUDED_DIMENSIONS, SummaryResource.DEFAULT_TIMEZONE_ID); responseMessage.put("cubeResults", cubeHighlights); return responseMessage; }
Source:
<code>public List<WorkspaceMetacardImpl> getWorkspaceMetacards(Set<String> workspaceIds) { <START> if (!workspaceIds.isEmpty()) { <END> final Filter filter = workspaceQueryBuilder.createFilter(workspaceIds); final QueryRequest queryRequest = createQueryRequest(filter); try { return createWorkspaceMetacards(catalogFramework.query(queryRequest)); } catch (UnsupportedQueryException | FederationException | SourceUnavailableException e) { LOGGER.warn("Error querying for workspaces: queryRequest={}", queryRequest, e); } } return Collections.emptyList(); }</code><technical_language>I suggest inverting predicate returning empty list early, while rid of larger indented code block</technical_language>

Target:
public List<WorkspaceMetacardImpl> getWorkspaceMetacards(Set<String> workspaceIds) { if (workspaceIds.isEmpty()) { return Collections.emptyList(); } final Filter filter = workspaceQueryBuilder.createFilter(workspaceIds); final QueryRequest queryRequest = createQueryRequest(filter); try { return createWorkspaceMetacards(query(queryRequest)); } catch (CatalogQueryException e) { LOGGER.info("Error querying for workspaces: queryRequest={}", queryRequest, e); } return Collections.emptyList(); }
Source:
<code>public void close() throws IOException { <START> if (selectObjectContentResult != null) { <END> selectObjectContentResult.close(); selectObjectContentResult = null; selectObjectRequest = null; } }</code><technical_language>need check clear fields here, SelectObjectContentResult is a Closeable guarantees close() is idempotent: > If stream is closed invoking this method effect</technical_language>

Target:
public void close() throws IOException { selectObjectContentResult.close(); }
Source:
<code>public List<String> getSeedNodeIps(final boolean addExternal) { final List<String> seeds = CassandraFrameworkProtosUtils.getSeedNodeIps(clusterState.nodes()); <START> if (addExternal) seeds.addAll(clusterState.getExternalSeeds()); <END> return seeds; }</code><technical_language>Add curly braces if move statement line</technical_language>

Target:
public List<String> getSeedNodeIps(final boolean addExternal) { final List<String> seeds = CassandraFrameworkProtosUtils.getSeedNodeIps(clusterState.nodes()); if (addExternal) { seeds.addAll(seedManager.getSeeds()); } return seeds; }
Source:
<code>private Timeout scheduleTimeout(Duration timeoutDuration) { if (timeoutDuration.toNanos() > 0) { try { return this.timer.newTimeout( (Timeout timeout1) -> setFinalError( new DriverTimeoutException("Query timed out after " + timeoutDuration), null, -1), timeoutDuration.toNanos(), TimeUnit.NANOSECONDS); } catch (IllegalStateException e) { throw ("cannot be started once stopped".equals(e.getMessage())) ? new IllegalStateException("Session is closed") <START> : e; <END> } } else { return null; } }</code><technical_language>I guess started stopped message is a Netty implementation thing. stinks rely hope change</technical_language>

Target:
private Timeout scheduleTimeout(Duration timeoutDuration) { if (timeoutDuration.toNanos() > 0) { try { return this.timer.newTimeout( (Timeout timeout1) -> setFinalError( new DriverTimeoutException("Query timed out after " + timeoutDuration), null, -1), timeoutDuration.toNanos(), TimeUnit.NANOSECONDS); } catch (IllegalStateException e) { result.completeExceptionally( ("cannot be started once stopped".equals(e.getMessage())) ? new IllegalStateException("Session is closed") : e); } } return null; }
Source:
<code>protected static void cleanUpResources(String testName) { TestResources resources = testResources.remove(testName); if (resources != null) { for (Cleaner<?> cleaner : resources.getCleaners()) { try { cleaner.close(); } catch (Throwable t) { <START> log.errorf(t, "Error cleaning resource %s", cleaner.ref); <END> } } } }</code><technical_language>throw IllegalStateException notify test leaked some resource</technical_language>

Target:
protected static void cleanUpResources(String testName) { TestResources resources = testResources.remove(testName); if (resources != null) { for (Cleaner<?> cleaner : resources.getCleaners()) { try { cleaner.close(); } catch (Throwable t) { log.fatalf(t, "Error cleaning resource %s for test %s", cleaner.ref, testName); throw new IllegalStateException("Error cleaning resource " + cleaner.ref + " for test " + testName); } } } }
Source:
<code>private void sizeCheck() { <START> if(!parquetProperties.isEstimateNextSizeCheck()) { <END> rowCountForNextSizeCheck = rowCount + parquetProperties.getMinRowCountForPageSizeCheck(); return; } long minRecordToWait = Long.MAX_VALUE; for (ColumnWriterV2 writer : writers) { long usedMem = writer.getCurrentPageBufferedSize(); long rows = rowCount - writer.getRowsWrittenSoFar(); long remainingMem = pageSizeThreshold - usedMem; if (remainingMem <= thresholdTolerance) { writer.writePage(rowCount); remainingMem = pageSizeThreshold; } long rowsToFillPage = usedMem == 0 ? parquetProperties.getMaxRowCountForPageSizeCheck() : (long)((float)rows) / usedMem * remainingMem; if (rowsToFillPage < minRecordToWait) { minRecordToWait = rowsToFillPage; } } if (minRecordToWait == Long.MAX_VALUE) { minRecordToWait = parquetProperties.getMinRowCountForPageSizeCheck(); } rowCountForNextSizeCheck = rowCount + min( max(minRecordToWait / 2, parquetProperties.getMinRowCountForPageSizeCheck()), parquetProperties.getMaxRowCountForPageSizeCheck()); }</code><technical_language>This block sets next row count for a size check leaves out checking pages written. I this a page written a row group is flushed file is closed</technical_language>

Target:
private void sizeCheck() { long minRecordToWait = Long.MAX_VALUE; for (ColumnWriterV2 writer : writers) { long usedMem = writer.getCurrentPageBufferedSize(); long rows = rowCount - writer.getRowsWrittenSoFar(); long remainingMem = pageSizeThreshold - usedMem; if (remainingMem <= thresholdTolerance) { writer.writePage(rowCount); remainingMem = pageSizeThreshold; } long rowsToFillPage = usedMem == 0 ? parquetProperties.getMaxRowCountForPageSizeCheck() : (long)((float)rows) / usedMem * remainingMem; if (rowsToFillPage < minRecordToWait) { minRecordToWait = rowsToFillPage; } } if (minRecordToWait == Long.MAX_VALUE) { minRecordToWait = parquetProperties.getMinRowCountForPageSizeCheck(); } if(parquetProperties.isEstimateNextSizeCheck()) { rowCountForNextSizeCheck = rowCount + min( max(minRecordToWait / 2, parquetProperties.getMinRowCountForPageSizeCheck()), parquetProperties.getMaxRowCountForPageSizeCheck()); } else { rowCountForNextSizeCheck = rowCount + parquetProperties.getMinRowCountForPageSizeCheck(); } }
Source:
<code>public Iterator<NeighborInfo> iterator() { return new Iterator<NeighborInfo>() { private Iterator<Entry<VKmer, ReadIdSet>> it = edges.entrySet().iterator(); private NeighborInfo info = null; @Override public boolean hasNext() { return it.hasNext(); } @Override public NeighborInfo next() { if(info == null){ info = new NeighborInfo(et, it.next()); <START> }else{ <END> } info.set(et, it.next()); return info; } @Override public void remove() { it.remove(); } }; }</code><technical_language>is this else block for</technical_language>

Target:
public Iterator<NeighborInfo> iterator() { return new Iterator<NeighborInfo>() { private Iterator<Entry<VKmer, ReadIdSet>> it = edges.entrySet().iterator(); private NeighborInfo info = null; @Override public boolean hasNext() { return it.hasNext(); } @Override public NeighborInfo next() { if (info == null) { info = new NeighborInfo(et, it.next()); } info.set(et, it.next()); return info; } @Override public void remove() { it.remove(); } }; }
Source:
<code>public void trackDelayedMetricsTenant(String tenantid, List<Metric> delayedMetrics) { if (isTrackingDelayedMetrics) { String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s\n",tenantid); for (Metric metric : delayedMetrics) { <START> logMessage += String.format("%s has collectionTime %d\n", metric.getLocator().toString(), metric.getCollectionTime()); <END> } log.info(logMessage); } }</code><technical_language>Do worth printing time in human readable format? amount of delay</technical_language>

Target:
public void trackDelayedMetricsTenant(String tenantid, List<Metric> delayedMetrics) { if (isTrackingDelayedMetrics) { String logMessage = String.format("[TRACKER][DELAYED METRIC] Tenant sending delayed metrics %s", tenantid); log.info(logMessage); double delayedMinutes; long nowMillis = System.currentTimeMillis(); for (Metric metric : delayedMetrics) { delayedMinutes = (double)(nowMillis - metric.getCollectionTime()) / 1000 / 60; logMessage = String.format("[TRACKER][DELAYED METRIC] %s has collectionTime %s which is delayed by %.2f minutes", metric.getLocator().toString(), dateFormatter.format(new Date(metric.getCollectionTime())), delayedMinutes); log.info(logMessage); } } }