auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private ConditionalSchema.Builder buildConditionalSchema() { ConditionalSchema.Builder builder = ConditionalSchema.builder(); if (ls.schemaJson().containsKey("if")) { builder.ifSchema(loadChild(ls.schemaJson().require("if").requireObject()).build()); <START> } <END> if (ls.schemaJson().containsKey("then")) { builder.thenSchema(loadChild(ls.schemaJson().require("then").requireObject()).build()); } if (ls.schemaJson().containsKey("else")) { builder.elseSchema(loadChild(ls.schemaJson().require("else").requireObject()).build()); } return builder; }</code><technical_language>schema is object, a boolean. please call requireObject() here. Also, instead of explicit if a schemaJson().require("if") call replaced a maybe("if") call returns anOptional<JsonValue>. eg. line 371 - 373 replaced like: ls.schemaJson().maybe("if").map(this::loadChild).ifPresent(builder::ifSchema) for handling else</technical_language>

Target:
private ConditionalSchema.Builder buildConditionalSchema() { ConditionalSchema.Builder builder = ConditionalSchema.builder(); ls.schemaJson().maybe("if").map(this::loadChild).map(Schema.Builder::build).ifPresent(builder::ifSchema); ls.schemaJson().maybe("then").map(this::loadChild).map(Schema.Builder::build).ifPresent(builder::thenSchema); ls.schemaJson().maybe("else").map(this::loadChild).map(Schema.Builder::build).ifPresent(builder::elseSchema); return builder; }
Source:
<code><START> private static List<QueryHintValue> findQueryHints(Method method, Predicate<QueryHints> annotationFilter) { <END> List<QueryHintValue> queryHints = new ArrayList<>(); QueryHints queryHintsAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, QueryHints.class); if (queryHintsAnnotation != null && annotationFilter.test(queryHintsAnnotation)) { for (QueryHint hint : queryHintsAnnotation.value()) { queryHints.add(new QueryHintValue(hint.name(), hint.value())); } } QueryHint queryHintAnnotation = AnnotationUtils.findAnnotation(method, QueryHint.class); if (queryHintAnnotation != null) { queryHints.add(new QueryHintValue(queryHintAnnotation.name(), queryHintAnnotation.value())); } return Collections.unmodifiableList(queryHints); }</code><technical_language>collect hints in a MultiValueMap. way, avoid additional type</technical_language>

Target:
private static SimpleQueryHints findQueryHints(Method method, Predicate<QueryHints> annotationFilter) { SimpleQueryHints queryHints = new SimpleQueryHints(); QueryHints queryHintsAnnotation = AnnotatedElementUtils.findMergedAnnotation(method, QueryHints.class); if (queryHintsAnnotation != null && annotationFilter.test(queryHintsAnnotation)) { for (QueryHint hint : queryHintsAnnotation.value()) { queryHints.add(hint.name(), hint.value()); } } QueryHint queryHintAnnotation = AnnotationUtils.findAnnotation(method, QueryHint.class); if (queryHintAnnotation != null) { queryHints.add(queryHintAnnotation.name(), queryHintAnnotation.value()); } return queryHints; }
Source:
<code>public final void recordLabelCreated(final LabelCreatedEvent event) { addCallback(store.getMeta(event.getId(), event.getType()), new FutureCallback<Optional<LabelMeta>>() { @Override public void onSuccess(final Optional<LabelMeta> meta) { if (meta.isPresent()) { LOG.info("Indexing {}", meta.get()); addCallback(searchPlugin.indexLabelMeta(meta.get()), pluginError); } <START> LOG.error("Unable to fetch LabelMeta object for {}[{}]", <END> event.getId(), event.getType()); } @Override public void onFailure(final Throwable throwable) { LOG.error("Unable to fetch LabelMeta object for {}[{}]", event.getId(), event.getType(), throwable); } }); }</code><technical_language>Log warn info instead of error</technical_language>

Target:
public final void recordLabelCreated(final LabelCreatedEvent event) { addCallback(store.getMeta(event.getId(), event.getType()), new FutureCallback<Optional<LabelMeta>>() { @Override public void onSuccess(final Optional<LabelMeta> meta) { if (meta.isPresent()) { LOG.info("Indexing {}", meta.get()); addCallback(searchPlugin.indexLabelMeta(meta.get()), pluginError); } LOG.warn( "Unable to fetch LabelMeta object for {}[{}]. " + "Consider setting the meta description for better indexing.", event.getId(), event.getType()); } @Override public void onFailure(final Throwable throwable) { LOG.error("Unable to fetch LabelMeta object for {}[{}]", event.getId(), event.getType(), throwable); } }); }
Source:
<code>public void registerStore(final StateStore store, final StateRestoreCallback stateRestoreCallback) { final String storeName = store.name(); if (CHECKPOINT_FILE_NAME.equals(storeName)) { throw new IllegalArgumentException(format("%sIllegal store name: %s, which collides with the pre-defined " + "checkpoint file name", logPrefix, storeName)); } if (stores.containsKey(storeName)) { <START> log.warn("State Store has already been registered, which could be due to a half-way registration" + <END> "in the previous round", storeName); } final String topic = storeToChangelogTopic.get(storeName); if (topic != null) { final TopicPartition storePartition = new TopicPartition(topic, taskId.partition); final StateStoreMetadata storeMetadata = new StateStoreMetadata( store, storePartition, stateRestoreCallback, converterForStore(store)); stores.put(storeName, storeMetadata); changelogReader.register(storePartition, this); } else { stores.put(storeName, new StateStoreMetadata(store)); } log.debug("Registered state store to its state manager", storeName); }</code><technical_language>I want skip re-registration higher call stack. In StateManagerUtil#registerStateStores call store.init store ultimately results in this registerStore called</technical_language>

Target:
public void registerStore(final StateStore store, final StateRestoreCallback stateRestoreCallback) { final String storeName = store.name(); if (CHECKPOINT_FILE_NAME.equals(storeName)) { throw new IllegalArgumentException(format("%sIllegal store name: %s, which collides with the pre-defined " + "checkpoint file name", logPrefix, storeName)); } if (stores.containsKey(storeName)) { throw new IllegalArgumentException(format("%sStore %s has already been registered.", logPrefix, storeName)); } final String topic = storeToChangelogTopic.get(storeName); if (topic != null) { final TopicPartition storePartition = new TopicPartition(topic, taskId.partition); final StateStoreMetadata storeMetadata = new StateStoreMetadata( store, storePartition, stateRestoreCallback, converterForStore(store)); stores.put(storeName, storeMetadata); changelogReader.register(storePartition, this); } else { stores.put(storeName, new StateStoreMetadata(store)); } log.debug("Registered state store to its state manager", storeName); }
Source:
<code>public void test_Han_Latin() throws Exception { Transliterator t = Transliterator.getInstance("Han-Latin"); assertEquals("hàn zì/hàn zì", t.transliterate("汉字/漢字")); assertEquals("chén", t.transliterate("\u6c88")); assertEquals("shěn", t.transliterate("\u700b")); <START> assertEquals("gǔ", t.transliterate("\u8d3e")); <END> t = Transliterator.getInstance("Han-Latin/Names"); assertEquals("shěn", t.transliterate("\u6c88")); assertEquals("shěn", t.transliterate("\u700b")); assertEquals("gǔ", t.transliterate("\u8d3e")); t = Transliterator.getInstance("Han-Latin/Names; Latin-Ascii; Any-Upper"); assertEquals("SHEN", t.transliterate("\u6c88")); assertEquals("SHEN", t.transliterate("\u700b")); assertEquals("GU", t.transliterate("\u8d3e")); }</code><technical_language>not. Han translit changes bugs. In Google CLDR & ICU a patch for this I think, CLDR 30.0.3 / ICU 58.2 a more complete fix</technical_language>

Target:
public void test_Han_Latin() throws Exception { Transliterator t = Transliterator.getInstance("Han-Latin"); assertEquals("hàn zì/hàn zì", t.transliterate("汉字/漢字")); assertEquals("chén", t.transliterate("\u6c88")); assertEquals("shěn", t.transliterate("\u700b")); assertEquals("jiǎ", t.transliterate("\u8d3e")); t = Transliterator.getInstance("Han-Latin/Names"); assertEquals("shěn", t.transliterate("\u6c88")); assertEquals("shěn", t.transliterate("\u700b")); assertEquals("jiǎ", t.transliterate("\u8d3e")); t = Transliterator.getInstance("Han-Latin/Names; Latin-Ascii; Any-Upper"); assertEquals("SHEN", t.transliterate("\u6c88")); assertEquals("SHEN", t.transliterate("\u700b")); assertEquals("JIA", t.transliterate("\u8d3e")); }
Source:
<code>public byte[] serialize(Object object) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); } catch (IOException e) { <START> throw new RuntimeException("NotSerializable object is: " + object.toString(), e); <END> } return bos.toByteArray(); }</code><technical_language>Suggest: "Failed serialize object: " + object.toString()</technical_language>

Target:
public byte[] serialize(Object object) { ByteArrayOutputStream bos = new ByteArrayOutputStream(); try { ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(object); oos.flush(); } catch (IOException e) { throw new RuntimeException("Failed to serialize object: " + object.toString(), e); } return bos.toByteArray(); }
Source:
<code>public DataObjectDeletedEvent( Project currentProject, DataObject currentDataObject ) { <START> super( null, currentProject, currentDataObject ); <END> }</code><technical_language>a lover of passing nulls methods constructors.. another constructor contextId better</technical_language>

Target:
public DataObjectDeletedEvent( Project currentProject, DataObject currentDataObject ) { super( currentProject, currentDataObject ); }
Source:
<code>public void testCloneWhenSourceIsInputData() { final InputData source = buildInputData(); setLinks(source, FIRST_URL, SECOND_URL); final InputData cloned = dmnDeepCloneProcess.clone(source, new InputData()); assertThat(cloned).isNotNull(); assertThat(cloned.getId().getValue()).isNotEqualTo(SOURCE_ID); assertThat(cloned.getName().getValue()).isEqualTo(INPUT_DATA_NAME); assertThat(cloned.getVariable().getTypeRef()).isEqualTo(BuiltInType.STRING.asQName()); <START> assertThat(cloned.getLinksHolder().getValue().getLinks()).hasSize(2); assertThat(cloned.getLinksHolder().getValue().getLinks()).first().extracting("url").isEqualTo(FIRST_URL); <END> }</code><technical_language>miss test for link: java assertThat(cloned.getLinksHolder().getValue().getLinks()) .extracting("url") .containsExactly(FIRST_URL, SECOND_URL); class, please URLs in tests (where applicable)</technical_language>

Target:
public void testCloneWhenSourceIsInputData() { final InputData source = buildInputData(); setLinks(source, FIRST_URL, SECOND_URL); final InputData cloned = dmnDeepCloneProcess.clone(source, new InputData()); assertThat(cloned).isNotNull(); assertThat(cloned.getId().getValue()).isNotEqualTo(SOURCE_ID); assertThat(cloned.getName().getValue()).isEqualTo(INPUT_DATA_NAME); assertThat(cloned.getVariable().getTypeRef()).isEqualTo(BuiltInType.STRING.asQName()); assertThat(cloned.getLinksHolder().getValue().getLinks()) .hasSize(2) .extracting(DMNExternalLink::getUrl).contains(FIRST_URL, SECOND_URL); }
Source:
<code>public XYTimeQueryFilter(long start, long end, int n, Collection<Long> entryIds) { super(start, end, n); <START> fEntryIds = entryIds; <END> }</code><technical_language>defensive copy</technical_language>

Target:
public XYTimeQueryFilter(long start, long end, int n, Collection<Long> entryIds) { super(start, end, n); fEntryIds = Collections.unmodifiableCollection(entryIds); }
Source:
<code>protected Config createConfig() { <START> Config config = new Config(); <END> config.setProperty(GroupProperty.MEMCACHE_ENABLED.getName(), "true"); JoinConfig join = config.getNetworkConfig().getJoin(); join.getMulticastConfig().setEnabled(false); join.getTcpIpConfig().setEnabled(false); return config; }</code><technical_language>improvement current state of this test, initialize config smallInstanceConfig() (also in MemcachedMultiendpointTest)</technical_language>

Target:
protected Config createConfig() { Config config = smallInstanceConfig(); config.setProperty(GroupProperty.MEMCACHE_ENABLED.getName(), "true"); JoinConfig join = config.getNetworkConfig().getJoin(); join.getMulticastConfig().setEnabled(false); join.getTcpIpConfig().setEnabled(false); return config; }
Source:
<code>protected TestInstanceFactory resolveTestInstanceFactory(ExtensionRegistry registry, ExtensionRegistry parentRegistry) { List<TestInstanceFactory> factories = registry.getExtensions(TestInstanceFactory.class); if (factories.isEmpty()) { return null; } if (parentRegistry != null) { List<TestInstanceFactory> parentFactories = parentRegistry.getExtensions(TestInstanceFactory.class); factories.removeAll(parentFactories); } if (factories.size() > 1) { String factoryNames = factories.stream().map(factory -> factory.getClass().getSimpleName()).collect( Collectors.joining(",")); String errorMessage = String.format( "Too many TestInstanceFactory extensions [%s] registered on test class: %s", factoryNames, testClass.getSimpleName()); <START> throw new JUnitException(errorMessage); <END> } return factories.get(0); }</code><technical_language>throw instance of ExtensionContextException</technical_language>

Target:
protected TestInstanceFactory resolveTestInstanceFactory(ExtensionRegistry registry, ExtensionRegistry parentRegistry) { List<TestInstanceFactory> factories = registry.getExtensions(TestInstanceFactory.class); if (factories.isEmpty()) { return null; } if (parentRegistry != null) { List<TestInstanceFactory> parentFactories = parentRegistry.getExtensions(TestInstanceFactory.class); factories.removeAll(parentFactories); } if (factories.size() > 1) { String factoryNames = factories.stream().map(factory -> factory.getClass().getSimpleName()).collect( Collectors.joining(",")); String errorMessage = String.format( "Too many TestInstanceFactory extensions [%s] registered on test class: %s (allowed is at most 1)", factoryNames, testClass.getSimpleName()); throw new ExtensionContextException(errorMessage); } return factories.get(0); }
Source:
<code>public void testPrepareObjectMapperWithNullObjectMapper() { try { DataFlowTemplate.prepareObjectMapper(null); } catch (IllegalArgumentException e) { assertEquals("The objectMapper must not be null.", e.getMessage()); return; } <START> fail("Expected an IllegalArgumentException to be thrown."); <END> }</code><technical_language>move fail try block. consistent other changes</technical_language>

Target:
public void testPrepareObjectMapperWithNullObjectMapper() { try { DataFlowTemplate.prepareObjectMapper(null); fail("Expected an IllegalArgumentException to be thrown."); } catch (IllegalArgumentException e) { assertEquals("The objectMapper must not be null.", e.getMessage()); return; } }
Source:
<code>public RestartRequirement onApply(UserPrefs prefs) { RestartRequirement restartRequirement = super.onApply(prefs); prefs_.ansiConsoleMode().setGlobalValue(consoleColorMode_.getValue()); if (prefs_.highlightConsoleErrors().getValue() != initialHighlightConsoleErrors_) { initialHighlightConsoleErrors_ = prefs_.highlightConsoleErrors().getValue(); restartRequirement.setRestartRequired(); } if (!restartRequirement.getDesktopRestartRequired() && !restartRequirement.getUiReloadRequired()) { if (prefs_.limitVisibleConsole().getValue() != initialLimitVisibleConsole_) { initialLimitVisibleConsole_ = prefs_.limitVisibleConsole().getValue(); <START> if (Desktop.isDesktop()) <END> restartRequirement.setDesktopRestartRequired(true); else restartRequirement.setUiReloadRequired(true); } } return restartRequirement; }</code><technical_language>replace this if/else a single call restartRequirement.setRestartRequired() (added recently)</technical_language>

Target:
public RestartRequirement onApply(UserPrefs prefs) { RestartRequirement restartRequirement = super.onApply(prefs); prefs_.ansiConsoleMode().setGlobalValue(consoleColorMode_.getValue()); if (prefs_.highlightConsoleErrors().getValue() != initialHighlightConsoleErrors_) { initialHighlightConsoleErrors_ = prefs_.highlightConsoleErrors().getValue(); restartRequirement.setRestartRequired(); } if (!restartRequirement.getDesktopRestartRequired() && !restartRequirement.getUiReloadRequired()) { if (prefs_.limitVisibleConsole().getValue() != initialLimitVisibleConsole_) { initialLimitVisibleConsole_ = prefs_.limitVisibleConsole().getValue(); restartRequirement.setRestartRequired(); } } return restartRequirement; }
Source:
<code><START> public Optional<Iterable<String>> getFlags(String field) { <END> Optional<String> value = delegate.getValue(SECTION_NAME, field); return value.map(input -> Splitter.on(" ").split(input.trim())); }</code><technical_language>mark this private</technical_language>

Target:
private Optional<Iterable<String>> getFlags(String field) { Optional<String> value = delegate.getValue(SECTION_NAME, field); return value.map(input -> Splitter.on(" ").split(input.trim())); }
Source:
<code>public static String toArrayTypeString(ArrayType type, Context context) { TypeMirror componentMirror = type.getComponentType(); if ( !componentMirror.getAnnotationMirrors().isEmpty() ) { TypeMirror component = type.getComponentType().accept( new SimpleTypeVisitor6<TypeMirror, Void>() { @Override protected TypeMirror defaultAction(TypeMirror e, Void aVoid) { return e; } }, null ); return extractClosestRealTypeAsString( component, context ) + "[]"; } <START> return toTypeString( type ); <END> }</code><technical_language>in this case, returning array type</technical_language>

Target:
public static String toArrayTypeString(ArrayType type, Context context) { TypeMirror component = type.getComponentType().accept( new SimpleTypeVisitor6<TypeMirror, Void>() { @Override protected TypeMirror defaultAction(TypeMirror e, Void aVoid) { return e; } }, null ); return extractClosestRealTypeAsString( component, context ) + "[]"; }
Source:
<code>public LookupsStateWithMap getLookupStateForNode( HostAndPort node ) throws IOException, InterruptedException, ExecutionException { final URL url = getLookupsURL(node); final AtomicInteger returnCode = new AtomicInteger(0); final AtomicReference<String> reasonString = new AtomicReference<>(null); LOG.debug("Getting lookups from [%s]", url); try (final InputStream result = httpClient.go( new Request(HttpMethod.GET, url) .addHeader(HttpHeaders.Names.ACCEPT, SmileMediaTypes.APPLICATION_JACKSON_SMILE), makeResponseHandler(returnCode, reasonString), lookupCoordinatorManagerConfig.getHostTimeout() ).get()) { <START> if (returnCode.get() == 200) { <END> try { final LookupsStateWithMap response = smileMapper.readValue(result, LookupsStateWithMap.class); LOG.debug( "Get on [%s], Status: %s reason: [%s], Response [%s].", url, returnCode.get(), reasonString.get(), response ); return response; } catch(IOException ex) { throw new IOE( ex, "Failed to parser GET lookups response from [%s]. response [%s].", url, result ); } } else { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { StreamUtils.copyAndClose(result, baos); } catch (IOException ex) { LOG.warn(ex, "Error reading response from GET on url [%s]", url); } throw new IOE( "GET request failed to [%s] : [%d] : [%s] Response: [%s]", url, returnCode.get(), reasonString.get(), StringUtils.fromUtf8(baos.toByteArray()) ); } } }</code><technical_language>Consider HttpUrlConnection.HTTP_OK constant instead</technical_language>

Target:
public LookupsState<LookupExtractorFactoryMapContainer> getLookupStateForNode( HostAndPort node ) throws IOException, InterruptedException, ExecutionException { final URL url = getLookupsURL(node); final AtomicInteger returnCode = new AtomicInteger(0); final AtomicReference<String> reasonString = new AtomicReference<>(null); LOG.debug("Getting lookups from [%s]", url); try (final InputStream result = httpClient.go( new Request(HttpMethod.GET, url) .addHeader(HttpHeaders.Names.ACCEPT, SmileMediaTypes.APPLICATION_JACKSON_SMILE), makeResponseHandler(returnCode, reasonString), lookupCoordinatorManagerConfig.getHostTimeout() ).get()) { if (returnCode.get() == HttpURLConnection.HTTP_OK) { try { final LookupsState<LookupExtractorFactoryMapContainer> response = smileMapper.readValue( result, LOOKUPS_STATE_TYPE_REFERENCE ); LOG.debug( "Get on [%s], Status: %s reason: [%s], Response [%s].", url, returnCode.get(), reasonString.get(), response ); return response; } catch(IOException ex) { throw new IOE( ex, "Failed to parser GET lookups response from [%s]. response [%s].", url, result ); } } else { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { StreamUtils.copyAndClose(result, baos); } catch (IOException ex) { LOG.warn(ex, "Error reading response from GET on url [%s]", url); } throw new IOE( "GET request failed to [%s] : [%d] : [%s] Response: [%s]", url, returnCode.get(), reasonString.get(), StringUtils.fromUtf8(baos.toByteArray()) ); } } }
Source:
<code>public void deleteSlideshow() { new ArticleContent().push( "<gallery type=\"slideshow\">\nImage010.jpg\ndefault_Image009.jpg\ndefault_Image008.jpg\ndefault_Image007.jpg\n" <START> + "Image010.jpg\ndefault_Image009.jpg\ndefault_Image008.jpg\ndefault_Image007.jpg\ndefault_Image006.jpg\ndefault_Image005.jpg\n" <END> + "default_Image004.jpg\ndefault_Image003.jpg\n</gallery>"); VisualEditModePageObject visualEditMode = new VisualEditModePageObject().open(); visualEditMode.removeComponent(Components.SLIDESHOW); visualEditMode.verifyComponentRemoved(Components.SLIDESHOW); }</code><technical_language>Image010 in test</technical_language>

Target:
public void deleteSlideshow() { new ArticleContent().push( "<gallery type=\"slideshow\">\ndefault_Image010.jpg\ndefault_Image009.jpg\ndefault_Image008.jpg\ndefault_Image007.jpg\n" + "default_Image010.jpg\ndefault_Image009.jpg\ndefault_Image008.jpg\ndefault_Image007.jpg\ndefault_Image006.jpg\ndefault_Image005.jpg\n" + "default_Image004.jpg\ndefault_Image003.jpg\n</gallery>"); VisualEditModePageObject visualEditMode = new VisualEditModePageObject().open(); visualEditMode.removeComponent(Components.SLIDESHOW); visualEditMode.verifyComponentRemoved(Components.SLIDESHOW); }
Source:
<code>protected float getAssignmentScore(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { <START> float estimatedMaxPartitionCount = clusterContext.getEstimatedMaxPartitionCount(); <END> float currentPartitionCount = node.getAssignedReplicaCount(); return computeUtilizationScore(estimatedMaxPartitionCount, currentPartitionCount); }</code><technical_language>Q: double increased weight</technical_language>

Target:
protected double getAssignmentScore(AssignableNode node, AssignableReplica replica, ClusterContext clusterContext) { int estimatedMaxPartitionCount = clusterContext.getEstimatedMaxPartitionCount(); int currentPartitionCount = node.getAssignedReplicaCount(); return computeUtilizationScore(estimatedMaxPartitionCount, currentPartitionCount); }
Source:
<code>public void testPushNetworkExceptionAndResend() throws NetworkException, InterruptedException { final CountDownLatch sendLatch = new CountDownLatch(1 + ParameterWorkerImpl.MAX_RESEND_COUNT); final long gracePeriod = 1000; doAnswer(invocationOnMock -> { sendLatch.countDown(); throw new NetworkException("exception"); }).when(mockSender).sendPushMsg(anyString(), any(EncodedKey.class), anyObject()); final int key = 0; new Thread(() -> { worker.push(key, key); <START> }).start(); <END> assertTrue(sendLatch.await(ParameterWorkerImpl.RESEND_INTERVAL_MS * ParameterWorkerImpl.MAX_RESEND_COUNT + gracePeriod, TimeUnit.MILLISECONDS)); verify(mockSender, times(1 + ParameterWorkerImpl.MAX_RESEND_COUNT)).sendPushMsg(anyString(), any(EncodedKey.class), anyObject()); }</code><technical_language>a micro optimization, avoid spawning thread Executor if possible</technical_language>

Target:
public void testPushNetworkExceptionAndResend() throws NetworkException, InterruptedException { final CountDownLatch sendLatch = new CountDownLatch(1 + ParameterWorkerImpl.MAX_RESEND_COUNT); final long gracePeriodMs = 100; final ExecutorService pool = Executors.newSingleThreadExecutor(); doAnswer(invocationOnMock -> { sendLatch.countDown(); throw new NetworkException("exception"); }).when(mockSender).sendPushMsg(anyString(), any(EncodedKey.class), anyObject()); final int key = 0; pool.execute(() -> worker.push(key, key)); pool.shutdown(); assertTrue(sendLatch.await((ParameterWorkerImpl.RESEND_INTERVAL_MS + gracePeriodMs) * ParameterWorkerImpl.MAX_RESEND_COUNT, TimeUnit.MILLISECONDS)); END_COUNT resend). verify(mockSender, times(1 + ParameterWorkerImpl.MAX_RESEND_COUNT)).sendPushMsg(anyString(), any(EncodedKey.class), anyObject()); }
Source:
<code>public BaseIlluminaDataProvider(final int lane, final OutputMapping outputMapping) { numReads = outputMapping.numOutputReads(); this.lane = lane; this.outputReadTypes = new ReadType[numReads]; final int[] i = {0}; <START> outputMapping.getOutputDescriptors().forEach(rd -> outputReadTypes[i[0]++] = rd.type); <END> }</code><technical_language>In this case IMO original code (using a for loop) easier read. Or, java streams do: outputReadTypes = StreamSupport.stream(outputMapping.getOutputDescriptors().spliterator(), false) .map(rd -> rd.type).toArray(ReadType[]::new); a shame direct Iterable -> Stream API this bad</technical_language>

Target:
public BaseIlluminaDataProvider(final int lane, final OutputMapping outputMapping) { numReads = outputMapping.numOutputReads(); this.lane = lane; this.outputReadTypes = StreamSupport.stream(outputMapping.getOutputDescriptors().spliterator(), false) .map(rd -> rd.type).toArray(ReadType[]::new); }
Source:
<code>public Map<Operation, Collection<Variable>> getOperations(View view) { String viewName = view.getName(); if (viewOperations.containsKey(viewName)) { Map<Operation, Collection<Variable>> operations = viewOperations.get(viewName); if (operations != null && operations.size() > 0) return operations; } <START> return null; <END> }</code><technical_language>If a hasOperations() method, throw a NoSuchViewException instead of returning null</technical_language>

Target:
public Map<Operation, Collection<Variable>> getOperations(View view) { String viewName = view.getName(); if (viewOperations.containsKey(viewName)) { return viewOperations.get(viewName); } throw new NoSuchViewException(view.getName()); }
Source:
<code>private static Thread slowScan(final Connector c, final String tableName, final AtomicBoolean stop) { Thread thread = new Thread() { @Override public void run() { try { while (stop.get() == false) { Scanner s = c.createScanner(tableName, Authorizations.EMPTY); IteratorSetting is = new IteratorSetting(50, SlowIterator.class); SlowIterator.setSleepTime(is, 10); s.addScanIterator(is); Iterator<Entry<Key,Value>> iterator = s.iterator(); while (iterator.hasNext() && stop.get() == false) { iterator.next(); } <START> s.close(); <END> } } catch (Exception ex) { log.trace("{}", ex.getMessage(), ex); stop.set(true); } } }; return thread; }</code><technical_language>Another one</technical_language>

Target:
private static Thread slowScan(final Connector c, final String tableName, final AtomicBoolean stop) { Thread thread = new Thread() { @Override public void run() { try { while (stop.get() == false) { try (Scanner s = c.createScanner(tableName, Authorizations.EMPTY)) { IteratorSetting is = new IteratorSetting(50, SlowIterator.class); SlowIterator.setSleepTime(is, 10); s.addScanIterator(is); Iterator<Entry<Key,Value>> iterator = s.iterator(); while (iterator.hasNext() && stop.get() == false) { iterator.next(); } } } } catch (Exception ex) { log.trace("{}", ex.getMessage(), ex); stop.set(true); } } }; return thread; }
Source:
<code>public Response processRequest(String requestId, Optional<RequestAction> maybeAction) throws InterruptedException { final Optional<BaragonRequest> maybeRequest = requestDatastore.getRequest(requestId); if (!maybeRequest.isPresent()) { return Response.status(Response.Status.NOT_FOUND).entity(String.format("Request %s does not exist", requestId)).build(); } final BaragonRequest request = maybeRequest.get(); RequestAction action = maybeAction.or(request.getAction().or(RequestAction.UPDATE)); Optional<BaragonService> maybeOldService = getOldService(request); try { LOG.info(String.format("Received request to %s with id %s", action, requestId)); switch (action) { case DELETE: return delete(request, maybeOldService); case RELOAD: return reload(); case REVERT: return revert(request, maybeOldService); default: return apply(request, maybeOldService); } } catch (LockTimeoutException e) { <START> LOG.error(String.format("Could not acquire lock before timeout for request %s", requestId), e); <END> return Response.status(Response.Status.CONFLICT).build(); } catch (Exception e) { LOG.error(String.format("Caught exception while %sING for request %s", action, requestId), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(String.format("Caught exception while %sING for request %s: %s", action, requestId, e.getMessage())).build(); } finally { LOG.info(String.format("Done processing %s request: %s", action, requestId)); } }</code><technical_language>LOG.warn more sense, this necessarily a failure</technical_language>

Target:
public Response processRequest(String requestId, Optional<RequestAction> maybeAction) throws InterruptedException { final Optional<BaragonRequest> maybeRequest = requestDatastore.getRequest(requestId); if (!maybeRequest.isPresent()) { return Response.status(Response.Status.NOT_FOUND).entity(String.format("Request %s does not exist", requestId)).build(); } final BaragonRequest request = maybeRequest.get(); RequestAction action = maybeAction.or(request.getAction().or(RequestAction.UPDATE)); Optional<BaragonService> maybeOldService = getOldService(request); try { LOG.info(String.format("Received request to %s with id %s", action, requestId)); switch (action) { case DELETE: return delete(request, maybeOldService); case RELOAD: return reload(request); case REVERT: return revert(request, maybeOldService); default: return apply(request, maybeOldService); } } catch (LockTimeoutException e) { LOG.warn(String.format("Couldn't acquire agent lock for %s in %s ms", requestId, agentLockTimeoutMs), e); return Response.status(Response.Status.CONFLICT).entity(String.format("Couldn't acquire agent lock for %s in %s ms. Lock Info: %s", requestId, agentLockTimeoutMs, e.getLockInfo())).build(); } catch (Exception e) { LOG.error(String.format("Caught exception while %sING for request %s", action, requestId), e); return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(String.format("Caught exception while %sING for request %s: %s", action, requestId, e.getMessage())).build(); } finally { LOG.info(String.format("Done processing %s request: %s", action, requestId)); } }
Source:
<code>public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider arg2) throws IOException { <START> if(value.equals(new LocalDate(0,1,1))) { <END> gen.writeString((String)null); } else { gen.writeString(FORMATTER.print(value)); } }</code><technical_language>if allow planned date null this change needed</technical_language>

Target:
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider arg2) throws IOException { gen.writeString(FORMATTER.print(value)); }
Source:
<code><START> public String getQuestionSpecificEditFormHtml() { <END> if (qnNumber == 1) { FeedbackContributionQuestionDetails fcqd = new FeedbackContributionQuestionDetails(); return fcqd.getQuestionSpecificEditFormHtml(qnNumber); } else { FeedbackTextQuestionDetails ftq = new FeedbackTextQuestionDetails(); return ftq.getQuestionSpecificEditFormHtml(qnNumber); } }</code><technical_language>Pass FeedbackQuestionAttributes UI template class use. feedbackQuestion.getQuestionDetails().getQuestionSpecificEditFormHtml(qnNumber); > ---- Polymorphism :D</technical_language>

Target:
public String getQuestionSpecificEditFormHtml() { return feedbackQuestion.getQuestionDetails().getQuestionSpecificEditFormHtml(qnNumber); }
Source:
<code>static void validateRefreshRate(int refreshRate) { <START> if (0 != refreshRate && (RefreshRate.MIN > refreshRate || RefreshRate.MAX < refreshRate)) { <END> throw new IllegalArgumentException(String.format(Locale.US, "refreshRate '%d' is out of range.", refreshRate)); } }</code><technical_language>Also, NO_CACHING invalid is it? means... caching</technical_language>

Target:
static void validateRefreshRate(int refreshRate) { if (RefreshRate.NO_CACHING != refreshRate && (RefreshRate.MIN > refreshRate || RefreshRate.MAX < refreshRate)) { throw new IllegalArgumentException(String.format(Locale.US, "refreshRate '%d' is out of range.", refreshRate)); } }
Source:
<code>@Override public void clear() { super.clear(); for (RelOptRule rule : ImmutableList.copyOf(mapDescToRule.values())) { removeRule(rule); } this.classOperands.clear(); this.allSets.clear(); this.mapDigestToRel.clear(); this.mapRel2Subset.clear(); this.relImportances.clear(); this.ruleQueue.clear(); this.materializations.clear(); <START> this.latticeByName.clear(); <END> this.provenanceMap.clear(); }</code><technical_language>If choose add this method superclass (instead of mapRuleDescription) ovverride</technical_language>

Target:
@Override public void clear() { super.clear(); for (RelOptRule rule : getRules()) { removeRule(rule); } this.classOperands.clear(); this.allSets.clear(); this.mapDigestToRel.clear(); this.mapRel2Subset.clear(); this.prunedNodes.clear(); this.ruleQueue.clear(); this.materializations.clear(); this.latticeByName.clear(); this.provenanceMap.clear(); }
Source:
<code>public final Serializable getId() { if ( id instanceof DelayedPostInsertIdentifier ) { final Serializable eeId = session.getPersistenceContext().getEntry( instance ).getId(); return eeId instanceof DelayedPostInsertIdentifier ? null : eeId; } <START> return id; <END> }</code><technical_language>Is for session.getPersistenceContext().getEntry( instance ) null? If so, NPE thrown</technical_language>

Target:
public final Serializable getId() { if ( id instanceof DelayedPostInsertIdentifier ) { final EntityEntry entry = session.getPersistenceContext().getEntry( instance ); final Serializable eeId = entry == null ? null : entry.getId(); return eeId instanceof DelayedPostInsertIdentifier ? null : eeId; } return id; }
Source:
<code>public static <A> UniConstraintCollector<A, ?, Integer> sum(ToIntFunction<? super A> groupValueMapping) { return new DefaultUniConstraintCollector<>( () -> new int[1], (resultContainer, a) -> { int value = groupValueMapping.applyAsInt(a); if (value == 0) { <START> return NOOP; <END> } resultContainer[0] += value; return (() -> resultContainer[0] -= value); }, resultContainer -> resultContainer[0]); }</code><technical_language>this give a noticable performance boost? Is worth added cost in code readability? this occur? Remember constraints want for a dataset a constriantWeight of ZERO disabled/removed earlier</technical_language>

Target:
public static <A> UniConstraintCollector<A, ?, Integer> sum(ToIntFunction<? super A> groupValueMapping) { return new DefaultUniConstraintCollector<>( () -> new int[1], (resultContainer, a) -> { int value = groupValueMapping.applyAsInt(a); resultContainer[0] += value; return (() -> resultContainer[0] -= value); }, resultContainer -> resultContainer[0]); }
Source:
<code>public void setEyeHeight(Float eyeHeight) { <START> this.eyeHeight = eyeHeight; <END> }</code><technical_language>sense restrict eye height player height? check this</technical_language>

Target:
public void setEyeHeight(Float eyeHeight) { if (eyeHeight< this.height) this.eyeHeight = eyeHeight; }
Source:
<code><START> public Boolean isFileSizeValid() { <END> return getComponentModel().validFileSize; }</code><technical_language>here, this boolean</technical_language>

Target:
public boolean isFileSizeValid() { return getComponentModel().validFileSize; }
Source:
<code>private void revokeToken(final OAuth20RefreshToken token) { LOGGER.debug("Revoking token [{}]", token); getOAuthConfigurationContext().getTicketRegistry().deleteTicket(token); token.getAccessTokens().forEach(item-> { LOGGER.debug("Revoking Access Token related to Refresh Token [{}]", item, token); <START> getOAuthConfigurationContext().getTicketRegistry().deleteTicket(item); <END> }); }</code><technical_language>Remove log line, Call revokeToken instead in a lambda avoid duplicate code</technical_language>

Target:
private void revokeToken(final OAuth20RefreshToken token) { revokeToken(token.getId()); token.getAccessTokens().forEach(item-> { revokeToken(item); }); }
Source:
<code><START> public static OVirtNodeInfo[] get() { <END> final String delimiter = ":"; final String[] path = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String regex[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); log.debugFormat("NodeInfo: regex length {0} minimum length {1} path length {2}", regex.length, minimumVersion.length, path.length); if (regex.length != minimumVersion.length || regex.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } for (int i=0; i < regex.length; i++) { log.debugFormat("NodeInfo: regex {0} path {1}, minimumVersion {2}", regex[i], path[i], minimumVersion[i]); info.add(new OVirtNodeInfo(Pattern.compile(regex[i]), new File(path[i]), minimumVersion[i])); } return info.toArray(new OVirtNodeInfo[info.size()]); }</code><technical_language>I prefer split fetch logic of OvirtNodeInfo a class, in OvirtNodeInfo</technical_language>

Target:
public static List<OVirtNodeInfo> get() { final String delimiter = ":"; final String[] path = Config.resolveOVirtISOsRepositoryPath().split(delimiter); final String minimumVersion[] = Config.<String> GetValue(ConfigValues.OvirtInitialSupportedIsoVersion).split(delimiter); final String regex[] = Config.<String> GetValue(ConfigValues.OvirtIsoPrefix).split(delimiter); List<OVirtNodeInfo> info = new LinkedList<OVirtNodeInfo>(); log.debugFormat("NodeInfo: regex length {0} minimum length {1} path length {2}", regex.length, minimumVersion.length, path.length); if (regex.length != minimumVersion.length || regex.length != path.length) { throw new IllegalArgumentException("Illegal NodeInfo - length"); } for (int i=0; i < regex.length; i++) { log.debugFormat("NodeInfo: regex {0} path {1}, minimumVersion {2}", regex[i], path[i], minimumVersion[i]); info.add(new OVirtNodeInfo(Pattern.compile(regex[i]), new File(path[i]), minimumVersion[i])); } return info; }
Source:
<code>KieAssetsDropdownItem asKieAsset(final DMNIncludeModel dmnIncludeModel) { final String text = dmnIncludeModel.getModelName(); final String value = dmnIncludeModel.getNamespace(); <START> final Map<String, String> metaData = new HashMap<String, String>() {{ <END> put(PATH_METADATA, dmnIncludeModel.getPath()); put(SUBTEXT_METADATA, dmnIncludeModel.getModelPackage()); }}; return new KieAssetsDropdownItem(text, value, metaData); }</code><technical_language>Please this map initialization: java new Maps.Builder() .put(PATH_METADATA, dmnIncludeModel.getPath()) .put(SUBTEXT_METADATA, dmnIncludeModel.getModelPackage()) .build();</technical_language>

Target:
KieAssetsDropdownItem asKieAsset(final DMNIncludeModel dmnIncludeModel) { final String text = dmnIncludeModel.getModelName(); final String subText = dmnIncludeModel.getModelPackage(); final String value = dmnIncludeModel.getNamespace(); final Map<String, String> metaData = buildMetaData(dmnIncludeModel); return new KieAssetsDropdownItem(text, subText, value, metaData); }
Source:
<code>public boolean unRegister(String name) { if (asyncHttpClientMap.remove(name) == null) return false; else return true; <START> } <END></code><technical_language>return asyncHttpClientMap.remove(name) != null</technical_language>

Target:
public boolean unRegister(String name) { return asyncHttpClientMap.remove(name) != null; }
Source:
<code>public static int getTypeId(String type) { <START> return ID_MAP.get(type); <END> }</code><technical_language>need return -1 in null case (i.e. type is in-house one)</technical_language>

Target:
public static int getTypeId(String type) { return ID_MAP.getOrDefault(type, -1); }
Source:
<code>public void addMetadata(Map<String, String> metadata) { if (null != metadata) { metadata.forEach((k, v) -> { Element metadataElement = new Element("metadata"); metadataElement.setAttribute("id", k.trim()); <START> if (null != v) { <END> metadataElement.setText(v.trim()); } else { metadataElement.setText(""); } this._root.getChild(TAG_METADATA).addContent(metadataElement); }); } }</code><technical_language>I this change is in a PR generate a conflict</technical_language>

Target:
public void addMetadata(Map<String, String> metadata) { if (null != metadata) { metadata.forEach((k, v) -> { Element metadataElement = new Element("metadata"); metadataElement.setAttribute("id", k.trim()); metadataElement.setText(v.trim()); this._root.getChild(TAG_METADATA).addContent(metadataElement); }); } }
Source:
<code>protected List<? extends Message> dispatchCommand(CommandEnvelope command) { <START> idempotencyGuard.ensureIdempotence(command); <END> final CommandHandlerMethod method = thisClass().getHandler(command.getMessageClass()); final List<? extends Message> result = method.invoke(this, command.getMessage(), command.getCommandContext()); return result; }</code><technical_language>This is hard read. read idempotent twice. guard other public methods for checking? like? java idempotencyGuard.check(command);</technical_language>

Target:
protected List<? extends Message> dispatchCommand(CommandEnvelope command) { idempotencyGuard.check(command); final CommandHandlerMethod method = thisClass().getHandler(command.getMessageClass()); final List<? extends Message> messages = method.invoke(this, command.getMessage(), command.getCommandContext()); return from(messages).filter(nonEmpty()).toList(); }
Source:
<code>public boolean visit(@Nonnull JMethodCall call) { Collection<JMethod> targets = <START> call.getMethodId().getMethods(); <END> if (targets.size() != 1) { return false; } JMethod target = targets.iterator().next(); if (target.isAbstract() || target.isNative()) { return false; } boolean foundForceInline = false; for (JAnnotation annotation : target.getAnnotations()) { if (annotation.getType().getName().endsWith("ForceInline")) { foundForceInline = true; } } if (!foundForceInline) { return false; } call.addMarker(new InlineMarker(target)); return false; }</code><technical_language>I doubt this want, especially in presence of virtual methods/calls</technical_language>

Target:
public boolean visit(@Nonnull JMethodCall call) { Collection<JMethod> targets = call.getMethodId().getMethods(); if (targets.size() != 1) { return false; } JMethod target = targets.iterator().next(); if (target.isAbstract() || target.isNative()) { return false; } boolean foundForceInline = false; for (JAnnotation annotation : target.getAnnotations()) { if (BinarySignatureFormatter.getFormatter() .getName(annotation.getType()) .equals(NamingTools.getTypeSignatureName(ForceInline.class.getName()))) { foundForceInline = true; } } if (!foundForceInline) { return false; } call.addMarker(new InlineMarker(target)); return false; }
Source:
<code><START> public void setDefaultParseFilter(ParseFilter filter) { <END> log.debug("Loading parse filter: " + filter.getClass().getSimpleName()); defaultParseFilter = filter; }</code><technical_language>Lets methods internal for (package accessible)</technical_language>

Target:
protected void setDefaultParseFilter(ParseFilter filter) { log.debug("Setting Default filter: " + filter.getClass().getSimpleName()); defaultParseFilter = filter; }
Source:
<code>public void uncaughtException(Thread t, Throwable e) { client.autoNotify(e); if(originalHandler != null) { <START> originalHandler.uncaughtException(t, e); <END> } }</code><technical_language>problem I this is errors longer printed stderr. I instead this: java Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread t, Throwable e) { System.err.printf("Exception in thread \"%s\" ", t.getName()); e.printStackTrace(System.err); } });</technical_language>

Target:
public void uncaughtException(Thread t, Throwable e) { client.autoNotify(e); if(originalHandler != null) { originalHandler.uncaughtException(t, e); } else { System.err.printf("Exception in thread \"%s\" ", t.getName()); e.printStackTrace(System.err); } }
Source:
<code>void onSaveProfileClicked() { Timber.v("Attempting to save profile"); String firstName = firstNameEditText.getText().toString(); String lastName = lastNameEditText.getText().toString(); String email = emailEditText.getText().toString(); UserSpec spec = new UserSpec(); User user = new User(); <START> user.getData().attributes().firstName(firstName); <END> user.getData().attributes().lastName(lastName); user.getData().attributes().email(email); spec.create(new CreateUserRequest()); spec.update(user); userRepo.update(spec) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted( new Action0() { @Override public void call() { Timber.v("Profile saved"); ProfileEditView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.profile_saved)); Flow.get(view.getContext()).set(new HomeScreen()); } else { Timber.w("getView() null, cannot notify user of successful profile save"); } } } ) .doOnError( new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "Unable to save profile"); Bugsnag.notify(throwable); ProfileEditView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.error_saving_profile)); } else { Timber.w("getView() null, cannot notify user of failed profile save"); } } } ) .subscribe(); }</code><technical_language>edit, (never mind model fluent)</technical_language>

Target:
void onSaveProfileClicked() { Timber.v("Attempting to save profile"); String firstName = firstNameEditText.getText().toString(); String lastName = lastNameEditText.getText().toString(); String email = emailEditText.getText().toString(); UserSpec spec = new UserSpec(); User user = new User(); user.getData().attributes().firstName(firstName); user.getData().attributes().lastName(lastName); user.getData().attributes().email(email); spec.create(new CreateUserRequest()); spec.update(user); userRepo.update(spec) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted( new Action0() { @Override public void call() { Timber.v("Profile saved"); ProfileEditView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.profile_saved)); Flow.get(view.getContext()).set(new HomeScreen()); } else { Timber.w("getView() null, cannot notify user of successful profile save"); } } } ) .doOnError( new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "Unable to save profile"); Crashlytics.logException(throwable); ProfileEditView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.error_saving_profile)); } else { Timber.w("getView() null, cannot notify user of failed profile save"); } } } ) .subscribe(); }
Source:
<code>public DaoManager() { super(); InvisibleForUsersRule invisible = new InvisibleForUsersRule(new LoggedUser(null, null)); this.randomizer = new Random(); <START> this.session = null; <END> this.questionDao = new QuestionDAO(session, invisible); this.answerDao = new AnswerDAO(session, invisible); this.userDao = new UserDAO(session); this.tagDao = new TagDAO(session); this.loginMethodDao = new LoginMethodDAO(session); }</code><technical_language>session null</technical_language>

Target:
public DaoManager() { super(); InvisibleForUsersRule invisible = new InvisibleForUsersRule(new LoggedUser(null, null)); this.randomizer = new Random(); this.session = new ScriptSessionProvider().getInstance(); this.questionDao = new QuestionDAO(session, invisible); this.answerDao = new AnswerDAO(session, invisible); this.userDao = new UserDAO(session); this.tagDao = new TagDAO(session); this.loginMethodDao = new LoginMethodDAO(session); }