auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testGetOrComputeIfAbsentContention() throws InterruptedException { final OnHeapStore<Long, String> store = newStore(); <START> int threads = 5; <END> final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threads); Runnable runnable = new Runnable() { @Override public void run() { try { startLatch.await(); } catch (InterruptedException e) { fail("Got an exception waiting to start thread " + e); } try { ValueHolder<String> result = store.getOrComputeIfAbsent(42L, new Function<Long, ValueHolder<String>>() { @Override public ValueHolder<String> apply(Long aLong) { return new CopiedOnHeapValueHolder<String>("theAnswer!", System.currentTimeMillis(), -1, new IdentityCopier<String>()); } }); assertThat(result.value(), is("theAnswer!")); endLatch.countDown(); } catch (Exception e) { e.printStackTrace(); fail("Got an exception " + e); } } }; for (int i = 0; i < threads; i++) { new Thread(runnable).start(); } startLatch.countDown(); boolean result = endLatch.await(2, TimeUnit.SECONDS); if (!result) { fail("Wait expired before completion, logs should have exceptions"); } }</code><technical_language>why</technical_language>

Target:
public void testGetOrComputeIfAbsentContention() throws InterruptedException { final OnHeapStore<Long, String> store = newStore(); int threads = 10; final CountDownLatch startLatch = new CountDownLatch(1); final CountDownLatch endLatch = new CountDownLatch(threads); Runnable runnable = new Runnable() { @Override public void run() { try { startLatch.await(); } catch (InterruptedException e) { fail("Got an exception waiting to start thread " + e); } try { ValueHolder<String> result = store.getOrComputeIfAbsent(42L, new Function<Long, ValueHolder<String>>() { @Override public ValueHolder<String> apply(Long aLong) { return new CopiedOnHeapValueHolder<String>("theAnswer!", System.currentTimeMillis(), -1, new IdentityCopier<String>()); } }); assertThat(result.value(), is("theAnswer!")); endLatch.countDown(); } catch (Exception e) { e.printStackTrace(); fail("Got an exception " + e); } } }; for (int i = 0; i < threads; i++) { new Thread(runnable).start(); } startLatch.countDown(); boolean result = endLatch.await(2, TimeUnit.SECONDS); if (!result) { fail("Wait expired before completion, logs should have exceptions"); } }
Source:
<code>public void terminate() { for (PHPCheck check : checks) { <START> check.terminate(); <END> } }</code><technical_language>exception in analyseFile(...) a try/catch mechanism log error analysis fail. Here, exception in check.terminate(); fail analysis, I prefer a surrounding try/catch log error</technical_language>

Target:
public void terminate() { for (PHPCheck check : checks) { try { check.terminate(); } catch (Exception e) { LOG.warn("An error occurred while trying to terminate checks:", e); } } }
Source:
<code>public IMap throttleSubmissionMap() { final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast(); <START> final int timeout = Duration.parse(casProperties.getAuthn().getThrottle().getSchedule().getRepeatInterval()).toStandardSeconds().getSeconds(); <END> final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory(); LOGGER.debug("Creating to record failed logins for throttling with timeout set to [{}]", MAP_KEY, timeout); final MapConfig ipMapConfig = factory.buildMapConfig(hz, MAP_KEY, timeout); hazelcastInstance.getConfig().addMapConfig(ipMapConfig); return hazelcastInstance.getMap(MAP_KEY); }</code><technical_language>Beans.newDuration(). break existing defaults</technical_language>

Target:
public IMap throttleSubmissionMap() { final HazelcastTicketRegistryProperties hz = casProperties.getTicket().getRegistry().getHazelcast(); final long timeout = Beans.newDuration(casProperties.getAuthn().getThrottle().getSchedule().getRepeatInterval()).getSeconds(); final HazelcastConfigurationFactory factory = new HazelcastConfigurationFactory(); LOGGER.debug("Creating to record failed logins for throttling with timeout set to [{}]", MAP_KEY, timeout); final MapConfig ipMapConfig = factory.buildMapConfig(hz, MAP_KEY, timeout); hazelcastInstance.getConfig().addMapConfig(ipMapConfig); return hazelcastInstance.getMap(MAP_KEY); }
Source:
<code>public void endBucket(ComputationContext context, int bucketSize) { String commandId = getCurrentCommand().getId(); try { <START> String csv = out.toString(UTF_8.toString()); <END> String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); String header = csv.substring(0, csv.indexOf(recordSeparator)); String data = csv.substring(csv.indexOf(recordSeparator) + recordSeparator.length()); DataBucket dataBucket = new DataBucket(commandId, bucketSize, data.getBytes(UTF_8), header.getBytes(UTF_8), new byte[] {}); Record record = Record.of(commandId, BulkCodecs.getDataBucketCodec().encode(dataBucket)); context.produceRecord(OUTPUT_1, record); out = null; } catch (UnsupportedEncodingException e) { getLog().error(e, e); } }</code><technical_language>UTF_8.name() is more canonical</technical_language>

Target:
public void endBucket(ComputationContext context, int bucketSize) { String commandId = getCurrentCommand().getId(); try { String csv = out.toString(UTF_8.name()); String recordSeparator = CSVFormat.DEFAULT.getRecordSeparator(); String header = getHeader(csv, recordSeparator); String data = getData(csv, recordSeparator); DataBucket dataBucket = new DataBucket(commandId, bucketSize, data.getBytes(UTF_8), header.getBytes(UTF_8), new byte[0]); Record record = Record.of(commandId, BulkCodecs.getDataBucketCodec().encode(dataBucket)); context.produceRecord(OUTPUT_1, record); out = null; } catch (UnsupportedEncodingException e) { getLog().error(e, e); } }
Source:
<code>public void migrateHomeWorkParkingToFavorites() { FavouritesDbHelper favorites = ctx.getFavorites(); favorites.addFavoritePersonal(getHomePoint(),FavouritesDbHelper.HOME,getHomePointDescription().getName()); favorites.addFavoritePersonal(getWorkPoint(),FavouritesDbHelper.WORK,getWorkPointDescription().getName()); <START> if (OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class) != null) { <END> ParkingPositionPlugin parkingPositionPlugin = OsmandPlugin.getEnabledPlugin(ParkingPositionPlugin.class); if(parkingPositionPlugin != null) { favorites.addFavoritePersonal(parkingPositionPlugin.constructParkingPosition(), FavouritesDbHelper.PARKING, ""); } } }</code><technical_language>here, plugin class in settings. parking plugin migrate point lost upgrade</technical_language>

Target:
public void migrateHomeWorkParkingToFavorites() { FavouritesDbHelper favorites = ctx.getFavorites(); if (getHomePoint() != null) { favorites.setHomePoint(getHomePoint(), getHomePointDescription()); } if (getWorkPoint() != null) { favorites.setWorkPoint(getWorkPoint(), getWorkPointDescription()); } }
Source:
<code>public void onDisplay(NavigateEvent navigateEvent) { if (!tournamentListPane.getChildren().isEmpty()) { return; } tournamentDetailWebView.setContextMenuEnabled(false); webViewConfigurer.configureWebView(tournamentDetailWebView); tournamentService.getAllTournaments() .thenAccept(tournaments -> { boolean firstItemSelected = false; tournaments.sort((o1, o2) -> -o1.getCreatedAt().compareTo(o2.getCreatedAt())); for (TournamentBean tournamentBean : tournaments) { TournamentListItemController tournamentListItemController = createAndAddTournamentItem(tournamentBean); if (!firstItemSelected) { tournamentListItemController.onMouseClicked(); firstItemSelected = true; } } <START> }); <END> }</code><technical_language>Hier .exceptionall</technical_language>

Target:
public void onDisplay(NavigateEvent navigateEvent) { if (!tournamentListPane.getChildren().isEmpty()) { return; } tournamentDetailWebView.setContextMenuEnabled(false); webViewConfigurer.configureWebView(tournamentDetailWebView); tournamentService.getAllTournaments() .thenAccept(tournaments -> { Platform.runLater(() -> { boolean firstItemSelected = false; tournaments.sort((o1, o2) -> -o1.getCreatedAt().compareTo(o2.getCreatedAt())); for (TournamentBean tournamentBean : tournaments) { TournamentListItemController tournamentListItemController = createAndAddTournamentItem(tournamentBean); if (!firstItemSelected) { tournamentListItemController.onMouseClicked(); firstItemSelected = true; } } }); }).exceptionally(throwable -> { log.error("Tournaments could not be loaded", throwable); return null; }); }
Source:
<code>public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; <START> return new Boolean(!mapping.getField().isNullable()).toString(); <END> } return super.getText(element); }</code><technical_language>Boolean.valueOf avoid object instanciation</technical_language>

Target:
public String getText(final Object element) { if (element instanceof FieldToContractInputMapping) { final FieldToContractInputMapping mapping = (FieldToContractInputMapping) element; return Boolean.valueOf(!mapping.getField().isNullable()).toString(); } return super.getText(element); }
Source:
<code><START> public <T> Optional<T> get(EventContextKey<T> key) { <END> checkNotNull(key, "EventContextKey cannot be null"); return Optional.ofNullable((T) this.entries.get(key.getId())); }</code><technical_language>A <T> T require(EventContextKey<T> key) method (similar <LINK_0> great here</technical_language>

Target:
public <T> Optional<T> get(EventContextKey<T> key) { checkNotNull(key, "EventContextKey cannot be null"); return Optional.ofNullable((T) this.entries.get(key)); }
Source:
<code>public BVDesignTrialInstance(final Integer instanceNumber, final List<Map<String, String>> rows) { <START> super(); <END> this.instanceNumber = instanceNumber; this.rows = rows; }</code><technical_language>I guess calling super constructor is automatically done java</technical_language>

Target:
public BVDesignTrialInstance(final Integer instanceNumber, final List<Map<String, String>> rows) { this.instanceNumber = instanceNumber; this.rows = rows; }
Source:
<code>private static File getNativeLibraryFile(String libname) { String pathFormat = "/org/voltdb/native/%s/x86_64"; String libPath = null; if (System.getProperty("os.name").toLowerCase().contains("mac")) { libPath = String.format(pathFormat, "Mac"); <START> } else { <END> libPath = String.format(pathFormat, "Linux"); } String libFileName = System.mapLibraryName(libname); if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { if (System.getProperty("os.name").toLowerCase().contains("mac")) { libFileName = "lib" + libname + ".jnilib"; } if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { String msg = "Could not find library resource using path: " + libPath + "/" + libFileName; s_hostLog.warn(msg); throw new RuntimeException(msg); } } File tmpFilePath = new File(System.getProperty(VOLT_TMP_DIR, System.getProperty("java.io.tmpdir"))); if (s_hostLog.isDebugEnabled()) { s_hostLog.debug("Temp directory to which shared libs are extracted is: " + tmpFilePath.getAbsolutePath()); } try { return loadLibraryFile(libPath, libFileName, tmpFilePath.getAbsolutePath()); } catch(IOException e) { s_hostLog.error("Error loading Volt library file from jar", e); throw new RuntimeException(e); } }</code><technical_language>In a more ideal world, suggestion } else if (System.getProperty("os.name").toLowerCase().contains("linux")) { libPath = String.format(pathFormat, "Linux"); } else { throw new RuntimeError("Unsupported system: " + System.getProperty("os.name")); }</technical_language>

Target:
private static File getNativeLibraryFile(String libname) { String pathFormat = "/org/voltdb/native/%s/x86_64"; String libPath = null; String osName = System.getProperty("os.name").toLowerCase(); if (osName.contains("mac")) { libPath = String.format(pathFormat, "Mac"); } else if (osName.contains("linux")) { libPath = String.format(pathFormat, "Linux"); } else { throw new RuntimeException("Unsupported system: " + osName); } String libFileName = System.mapLibraryName(libname); if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { if (osName.contains("mac")) { libFileName = "lib" + libname + ".jnilib"; } if (NativeLibraryLoader.class.getResource(libPath + "/" + libFileName) == null) { String msg = "Could not find library resource using path: " + libPath + "/" + libFileName; s_hostLog.warn(msg); throw new RuntimeException(msg); } } File tmpFilePath = new File(System.getProperty(VOLT_TMP_DIR, System.getProperty("java.io.tmpdir"))); if (s_hostLog.isDebugEnabled()) { s_hostLog.debug("Temp directory to which shared libs are extracted is: " + tmpFilePath.getAbsolutePath()); } try { return loadLibraryFile(libPath, libFileName, tmpFilePath.getAbsolutePath()); } catch(IOException e) { s_hostLog.error("Error loading Volt library file from jar", e); throw new RuntimeException(e); } }
Source:
<code><START> public void clearPrivateMessageFields() { <END> this.toField.clear(); this.titleField.clear(); this.messageField.clear(); }</code><technical_language>forget logging, this save hours for in future :)</technical_language>

Target:
public void clearPrivateMessageFields() { info("Clearing all message fields."); this.toField.clear(); this.titleField.clear(); this.messageField.clear(); }
Source:
<code>public Response updateAssetRecord(@PathParam("nodeCriteria") final String nodeCriteria, final MultivaluedMapImpl params) { OnmsNode node = m_nodeDao.get(nodeCriteria); if (node == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Can't find node " + nodeCriteria); } OnmsAssetRecord assetRecord = getAssetRecord(node); if (assetRecord == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Node " + node + " could not update "); } if (assetRecord.getGeolocation() == null) { assetRecord.setGeolocation(new OnmsGeolocation()); } LOG.debug("updateAssetRecord: updating asset {}", assetRecord); boolean modified = false; BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(assetRecord); wrapper.registerCustomEditor(Date.class, new ISO8601DateEditor()); for(String key : params.keySet()) { if (wrapper.isWritableProperty(key)) { String stringValue = params.getFirst(key); Object value = wrapper.convertIfNecessary(stringValue, (Class<?>)wrapper.getPropertyType(key)); wrapper.setPropertyValue(key, value); modified = true; } } if (modified) { LOG.debug("updateAssetRecord: assetRecord updated", assetRecord); <START> m_assetRecordDao.update(assetRecord); <END> try { sendEvent(EventConstants.ASSET_INFO_CHANGED_EVENT_UEI, node.getId()); } catch (EventProxyException e) { throw getException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return Response.noContent().build(); } return Response.notModified().build(); }</code><technical_language>Is node asset record? In this case need a save instead of update</technical_language>

Target:
public Response updateAssetRecord(@PathParam("nodeCriteria") final String nodeCriteria, final MultivaluedMapImpl params) { OnmsNode node = m_nodeDao.get(nodeCriteria); if (node == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Can't find node " + nodeCriteria); } OnmsAssetRecord assetRecord = getAssetRecord(node); if (assetRecord == null) { throw getException(Status.BAD_REQUEST, "updateAssetRecord: Node " + node + " could not update "); } if (assetRecord.getGeolocation() == null) { assetRecord.setGeolocation(new OnmsGeolocation()); } LOG.debug("updateAssetRecord: updating asset {}", assetRecord); boolean modified = false; BeanWrapper wrapper = PropertyAccessorFactory.forBeanPropertyAccess(assetRecord); wrapper.registerCustomEditor(Date.class, new ISO8601DateEditor()); for(String key : params.keySet()) { if (wrapper.isWritableProperty(key)) { String stringValue = params.getFirst(key); Object value = wrapper.convertIfNecessary(stringValue, (Class<?>)wrapper.getPropertyType(key)); wrapper.setPropertyValue(key, value); modified = true; } } if (modified) { LOG.debug("updateAssetRecord: assetRecord updated", assetRecord); m_assetRecordDao.saveOrUpdate(assetRecord); try { sendEvent(EventConstants.ASSET_INFO_CHANGED_EVENT_UEI, node.getId()); } catch (EventProxyException e) { throw getException(Status.INTERNAL_SERVER_ERROR, e.getMessage()); } return Response.noContent().build(); } return Response.notModified().build(); }
Source:
<code>private void convert(JCas aJCas, PrintWriter aOut) { <START> int i = 30; <END> Type neType = JCasUtil.getType(aJCas, NamedEntity.class); Feature neValue = neType.getFeatureByBaseName("value"); IobEncoder neEncoder = new IobEncoder(aJCas.getCas(), neType, neValue, false); Map<Sentence, Collection<NamedEntity>> idx = JCasUtil.indexCovered(aJCas, Sentence.class, NamedEntity.class); Collection<NamedEntity> coveredNEs; for (Sentence sentence : select(aJCas, Sentence.class)) { if (i < 0) { break; } coveredNEs = idx.get(sentence); if (coveredNEs.isEmpty()) { continue; } HashMap<Token, Row> ctokens = new LinkedHashMap<>(); List<Token> tokens = selectCovered(Token.class, sentence); for (Token token : tokens) { Row row = new Row(); row.token = token; row.ne = neEncoder.encode(token); ctokens.put(row.token, row); } for (Row row : ctokens.values()) { aOut.printf("%s\t%s%n", row.token.getCoveredText(), row.ne); } aOut.println(); i--; } }</code><technical_language>This variable in anymore, right</technical_language>

Target:
private void convert(JCas aJCas, PrintWriter aOut) { Type neType = JCasUtil.getType(aJCas, NamedEntity.class); Feature neValue = neType.getFeatureByBaseName("value"); IobEncoder neEncoder = new IobEncoder(aJCas.getCas(), neType, neValue, false); Map<Sentence, Collection<NamedEntity>> idx = JCasUtil.indexCovered(aJCas, Sentence.class, NamedEntity.class); Collection<NamedEntity> coveredNEs; for (Sentence sentence : select(aJCas, Sentence.class)) { coveredNEs = idx.get(sentence); if (coveredNEs.isEmpty()) { continue; } HashMap<Token, Row> ctokens = new LinkedHashMap<>(); List<Token> tokens = selectCovered(Token.class, sentence); for (Token token : tokens) { Row row = new Row(); row.token = token; row.ne = neEncoder.encode(token); ctokens.put(row.token, row); } for (Row row : ctokens.values()) { aOut.printf("%s\t%s%n", row.token.getCoveredText(), row.ne); } aOut.println(); } }
Source:
<code>private DeviceKeyStoreRecord getRecordRemotely(final String deviceId) { if(DEFAULT_FACTORY_DEVICE_ID.equals(deviceId)) { LOGGER.warn("Device not properly provisioned, got as a deviceId", deviceId); throw new WebApplicationException(Response.Status.NOT_FOUND); } final HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(keyStoreTableName) .withKey(key); final GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest); LOGGER.info("getItemResult = {}", getItemResult.toString()); if(getItemResult.getItem() == null || !getItemResult.getItem().containsKey(AES_KEY_ATTRIBUTE_NAME)) { LOGGER.warn("Did not find anything for device_id = {}", deviceId); <START> throw new WebApplicationException(Response.Status.NOT_FOUND); <END> } final String aesKey = getItemResult.getItem().get(AES_KEY_ATTRIBUTE_NAME).getS(); final String metadata = getItemResult.getItem().get(METADATA).getS(); return new DeviceKeyStoreRecord(censorKey(aesKey), metadata); }</code><technical_language>throw webapplication in resource. Optional</technical_language>

Target:
private Optional<DeviceKeyStoreRecord> getRecordRemotely(final String deviceId) { if(DEFAULT_FACTORY_DEVICE_ID.equals(deviceId)) { LOGGER.warn("Device not properly provisioned, got as a deviceId", deviceId); return Optional.absent(); } final HashMap<String, AttributeValue> key = new HashMap<String, AttributeValue>(); key.put(DEVICE_ID_ATTRIBUTE_NAME, new AttributeValue().withS(deviceId)); final GetItemRequest getItemRequest = new GetItemRequest() .withTableName(keyStoreTableName) .withKey(key); final GetItemResult getItemResult = dynamoDBClient.getItem(getItemRequest); LOGGER.info("getItemResult = {}", getItemResult.toString()); if(getItemResult.getItem() == null || !getItemResult.getItem().containsKey(AES_KEY_ATTRIBUTE_NAME)) { LOGGER.warn("Did not find anything for device_id = {}", deviceId); return Optional.absent(); } final String aesKey = getItemResult.getItem().get(AES_KEY_ATTRIBUTE_NAME).getS(); final String metadata = getItemResult.getItem().get(METADATA).getS(); return Optional.of(new DeviceKeyStoreRecord(censorKey(aesKey), metadata)); }
Source:
<code>public void mainTest() { <START> String baseUrl = "localhost:8080/openmrs/ws/rest"; <END> String str = new SwaggerSpecificationCreator(baseUrl).BuildJSON(); assertNotNull(str); }</code><technical_language>this work 8080 port is some other process</technical_language>

Target:
public void mainTest() { String baseUrl = "host/openmrs/ws/rest"; String str = new SwaggerSpecificationCreator(baseUrl).BuildJSON(); assertNotNull(str); }
Source:
<code>public void disconnect() { <START> fControl.setState(TerminalState.CLOSED); <END> }</code><technical_language>Add a null check, class initialized yet</technical_language>

Target:
public void disconnect() { if (fControl != null) { fControl.setState(TerminalState.CLOSED); } }
Source:
<code>public Iterator<Tuple2<Long, Tuple2<byte[], byte[]>>> call(Iterator<KVPair> kvPairIterator) throws Exception { if (!kvPairIterator.hasNext()) return Collections.EMPTY_LIST.iterator(); List<Tuple2<Long, Tuple2<byte[], byte[]>>> outList = new ArrayList<>(); while (kvPairIterator.hasNext()) { KVPair kvPair = kvPairIterator.next(); if (kvPair == null) continue; Tuple2<byte[], byte[]> kv = new Tuple2(kvPair.getRowKey(), kvPair.getValue()); outList.add(new Tuple2(conglomerateId, kv)); } <START> return outList.iterator(); <END> }</code><technical_language>meaning materialize iterator a list? Is wrap iterator vs. materializing thing</technical_language>

Target:
public Iterator<Tuple2<Long, Tuple2<byte[], byte[]>>> call(Iterator<KVPair> kvPairIterator) throws Exception { return new NullFilterKVPairIterator(conglomerateId, kvPairIterator); }
Source:
<code>public InfoboxBuilderPage selectHeaderWithIndex(int index) { <START> wait.forElementVisible(headers.get(index)); <END> headers.get(index).click(); return this; }</code><technical_language>store WebElement in variable wait for clickable</technical_language>

Target:
public InfoboxBuilderPage selectHeaderWithIndex(int index) { WebElement selectedHeader = headers.get(index); wait.forElementClickable(selectedHeader); selectedHeader.click(); return this; }
Source:
<code>public void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws UnprocessableEntityException, PatchBadRequestException, AuthorizeException, ResourceNotFoundException { try { EPerson eperson = es.find(context, uuid); if (eperson == null) { throw new ResourceNotFoundException(apiCategory + "." + model + " with id: " + uuid + " not found"); } List<Operation> operations = patch.getOperations(); boolean isAdmin; try { isAdmin = authorizeService.isAdmin(context); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } for (Operation op: operations) { if (op.getPath().contentEquals("/canLogin") || op.getPath().contentEquals("/certificate") || op.getPath().contentEquals("/netid") <START> || op.getPath().contentEquals("/email")) { <END> if (!isAdmin) { throw new AuthorizeException(op.getPath() + " requires administrator."); } } } EPersonRest ePersonRest = findOne(context, uuid); EPersonRest patchedModel = (EPersonRest) epersonPatch.patch(ePersonRest, operations); updatePatchedValues(context, patchedModel, eperson); } catch (SQLException e) { throw new RuntimeException(e.getMessage(), e); } }</code><technical_language>for a user change e-mail address</technical_language>

Target:
protected void patch(Context context, HttpServletRequest request, String apiCategory, String model, UUID uuid, Patch patch) throws AuthorizeException, SQLException { patchDSpaceObject(apiCategory, model, uuid, patch); }
Source:
<code>public void shouldReturn404OnGetTransactionsWhenAccountIdIsNonNumeric() { getChargeApi .withAccountId("invalidAccountId") .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) <START> .getCharges() <END> .contentType(JSON) .statusCode(NOT_FOUND.getStatusCode()) .body("code", is(404)) .body("message", is("HTTP 404 Not Found")); }</code><technical_language>This test call a endpoint /v1/api/accounts/{accountId}/charges /v1/api/accounts/{accountId}/transactions. I want that</technical_language>

Target:
public void shouldReturn404OnGetTransactionsWhenAccountIdIsNonNumeric() { getChargeApi .withAccountId("invalidAccountId") .withHeader(HttpHeaders.ACCEPT, APPLICATION_JSON) .getTransactions() .contentType(JSON) .statusCode(NOT_FOUND.getStatusCode()) .body("code", is(404)) .body("message", is("HTTP 404 Not Found")); }
Source:
<code>void multipleReceiverAndAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int firstBatch = 2; int secondBatch = 2; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages; if (isSessionEnabled) { messages = TestUtils.getServiceBusMessages(firstBatch, CONTENTS_BYTES, messageId, isSessionEnabled, sessionId); messages.addAll(TestUtils.getServiceBusMessages(secondBatch, CONTENTS_BYTES, messageId, isSessionEnabled, sessionId2)); } else { messages = TestUtils.getServiceBusMessages(firstBatch + secondBatch, CONTENTS_BYTES, messageId, isSessionEnabled, null); } sendMessage(messages).block(TIMEOUT); StepVerifier.create(receiver.receive().limitRequest(firstBatch)) .assertNext(message -> { <START> messagesPending.decrementAndGet(); <END> }) .assertNext(message -> { messagesPending.decrementAndGet(); }) .thenCancel() .verify(); StepVerifier.create(receiver2.receive().limitRequest(secondBatch)) .assertNext(message -> { messagesPending.decrementAndGet(); }) .assertNext(message -> { messagesPending.decrementAndGet(); }) .thenCancel() .verify(); }</code><technical_language>assserting here</technical_language>

Target:
void multipleReceiverAndAutoComplete(MessagingEntityType entityType, boolean isSessionEnabled) { setSenderAndReceiver(entityType, isSessionEnabled); int firstBatch = 2; int secondBatch = 2; final String messageId = UUID.randomUUID().toString(); final List<ServiceBusMessage> messages; if (isSessionEnabled) { messages = TestUtils.getServiceBusMessages(firstBatch, CONTENTS_BYTES, messageId, sessionId); messages.addAll(TestUtils.getServiceBusMessages(secondBatch, CONTENTS_BYTES, messageId, sessionId2)); } else { messages = TestUtils.getServiceBusMessages(firstBatch + secondBatch, messageId, CONTENTS_BYTES); } sendMessage(messages).block(TIMEOUT); StepVerifier.create(receiver.receive(), firstBatch) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .thenCancel() .verify(); StepVerifier.create(receiver2.receive(), secondBatch) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .assertNext(message -> { assertMessageEquals(message, messageId, isSessionEnabled); messagesPending.decrementAndGet(); }) .thenCancel() .verify(); }
Source:
<code>public void handleBackpressure(CoreEvent event) { asyncQueue.offer(event); synchronized (asyncQueue) { asyncQueue.notify(); } synchronized (executing) { if (executing.get() != null) { <START> if (!executing.get().isDone()) { <END> return; } } executing.set(dispatchTask()); } }</code><technical_language>&&</technical_language>

Target:
public void handleBackpressure(CoreEvent event) { asyncQueue.offer(event); synchronized (executing) { if (executing.get() == null) { executing.set(dispatchTask()); } } }
Source:
<code>public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DynamicPomDependency)) { return false; } DynamicPomDependency that = (DynamicPomDependency) o; return getGroupID().equals(that.getGroupID()) && getArtifactID().equals(that.getArtifactID()) && getVersion().equals(that.getVersion()) && <START> Objects.equals(getScope(), <END> that.getScope()); }</code><technical_language>if Objects is avialble client side</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof DynamicPomDependency)) { return false; } DynamicPomDependency that = (DynamicPomDependency) o; if (!getGroupID().equals(that.getGroupID())) { return false; } if (!getArtifactID().equals(that.getArtifactID())) { return false; } if (!getVersion().equals(that.getVersion())) { return false; } return getScope() != null ? getScope().equals(that.getScope()) : that.getScope() == null; }
Source:
<code>public void testModelEnrichmentWhenTopLevelDecisionTableWithDecision() { <START> setupGraphWithDiagram(); setupGraphWithDecision(); <END> final Optional<DecisionTable> oModel = definition.getModelClass(); definition.enrich(Optional.of(NODE_UUID), decision, oModel); final DecisionTable model = oModel.get(); assertBasicEnrichment(model); final List<InputClause> input = model.getInput(); assertThat(input.size()).isEqualTo(1); assertThat(input.get(0).getInputExpression()).isInstanceOf(InputClauseLiteralExpression.class); assertThat(input.get(0).getInputExpression().getText().getValue()).isEqualTo(DECISION_NAME_1); assertThat(input.get(0).getInputExpression().getTypeRef()).isEqualTo(DECISION_QNAME_1); assertStandardOutputClauseEnrichment(model); assertStandardDecisionRuleEnrichment(model, 1, 1); assertParentHierarchyEnrichment(model, 1, 1); }</code><technical_language>I shooot leg, in this case I feeling source target parameters of method code more readable. WDYT</technical_language>

Target:
public void testModelEnrichmentWhenTopLevelDecisionTableWithDecision() { setupGraphWithDiagram(); setupGraphWithDecision(); final Optional<DecisionTable> oModel = definition.getModelClass(); definition.enrich(Optional.of(NODE_UUID), decision, oModel); final DecisionTable model = oModel.get(); assertBasicEnrichment(model); final List<InputClause> input = model.getInput(); assertThat(input.size()).isEqualTo(1); assertThat(input.get(0).getInputExpression()).isInstanceOf(InputClauseLiteralExpression.class); assertThat(input.get(0).getInputExpression().getText().getValue()).isEqualTo(DECISION_NAME_1); assertThat(input.get(0).getInputExpression().getTypeRef()).isEqualTo(DECISION_QNAME_1); assertStandardOutputClauseEnrichment(model); assertStandardDecisionRuleEnrichment(model); assertParentHierarchyEnrichment(model); }
Source:
<code>private void addAlert(VDS host, AuditLogType auditMessage) { AuditLogableBase logableBase = new AuditLogableBase(); <START> logableBase.addCustomValue("VdsName", host.getName()); <END> AlertDirector.addVdsAlert(host.getId(), auditMessage, auditLogDirector, logableBase); }</code><technical_language>IIRC if setVds(...) get getVdsName() setting a custom value, please try</technical_language>

Target:
private void addAlert(VDS host, AuditLogType auditMessage) { AuditLogableBase logableBase = Injector.injectMembers(new AuditLogableBase()); logableBase.setVds(host); AlertDirector.addVdsAlert(host.getId(), auditMessage, auditLogDirector, logableBase); }
Source:
<code>public static String encodeRow(String value) { <START> return getRowPrefix() + SortSkew.getCode(value) + value; <END> }</code><technical_language>getRowPrefix method private? externally</technical_language>

Target:
public static String encodeRow(String value) { return section.getRowPrefix() + SortSkew.getCode(value) + value; }
Source:
<code><START> private ArrayList<String> relationshipStringList(List<QueryParameters.SpatialRelationship> relationshipList) { <END> ArrayList<String> stringList = new ArrayList<>(); for (QueryParameters.SpatialRelationship relationship : relationshipList) { stringList.add(relationship.toString()); } return stringList; }</code><technical_language>method static</technical_language>

Target:
private static ArrayList<String> relationshipStringList(List<QueryParameters.SpatialRelationship> relationshipList) { ArrayList<String> stringList = new ArrayList<>(); for (QueryParameters.SpatialRelationship relationship : relationshipList) { stringList.add(relationship.toString()); } return stringList; }
Source:
<code>public void testOperationWithResponseExamples() { String openApiYAML = readIntoYaml(GetOperationWithResponseExamples.class); int start = openApiYAML.indexOf("get:"); int end = openApiYAML.length() - 1; String extractedYAML = openApiYAML.substring(start, end); String expectedYAML = "get:\n" + " summary: \"Simple get operation\"\n" + " description: \"Defines a simple get operation with no inputs and a complex output\"\n" + " operationId: \"getWithPayloadResponse\"\n" + " responses:\n" + " 200:\n" + " description: \"voila!\"\n" + " content:\n" + " application/json:\n" + " schema:\n" + " type: \"object\"\n" + " properties:\n" + " id:\n" + " type: \"string\"\n" + " description: \"the user id\"\n" + " examples:\n" + " basic:\n" + " summary: \"shows a basic example\"\n" + " description: \"basic\"\n" + <START> " value: \"{\\\"id\\\": 19877734}\"\n" + <END> " deprecated: true"; assertEquals(extractedYAML, expectedYAML); }</code><technical_language>This is right, parsed object shown escaped string</technical_language>

Target:
public void testOperationWithResponseExamples() { String openApiYAML = readIntoYaml(GetOperationWithResponseExamples.class); int start = openApiYAML.indexOf("get:"); int end = openApiYAML.indexOf("components:"); String extractedYAML = openApiYAML.substring(start, end); String expectedYAML = "get:\n" + " summary: \"Simple get operation\"\n" + " description: \"Defines a simple get operation with no inputs and a complex output\"\n" + " operationId: \"getWithPayloadResponse\"\n" + " responses:\n" + " 200:\n" + " description: \"voila!\"\n" + " content:\n" + " application/json:\n" + " schema:\n" + " $ref: \"#/components/schemas/SampleResponseSchema\"\n" + " examples:\n" + " basic:\n" + " summary: \"shows a basic example\"\n" + " description: \"basic\"\n" + " value:\n" + " id: 19877734\n" + " deprecated: true\n"; assertEquals(extractedYAML, expectedYAML); }
Source:
<code>public AssetField[] getAssetFieldsForAddress(final InetAddress address, final String vendor) { getReadLock().lock(); try { if (vendor == null) { LOG.debug("getAssetFieldsForAddress: WSMAN vendor field was null for address {}, returning empty list", InetAddressUtils.str(address)); return new AssetField[0]; } final List<AssetField> retval = new ArrayList<>(); for (final org.opennms.netmgt.config.wsmanAsset.adapter.Package pkg : m_config.getPackages()) { final String pkgVendor = pkg.getVendor(); if (pkgVendor != null) { if (pkgVendor.equals(vendor)) { retval.addAll(pkg.getAssetFields()); } } } <START> if (retval.size() == 0) { <END> LOG.debug("getAssetFieldsForAddress: Zero AssetField matches returned for with vendor: {}", InetAddressUtils.str(address), vendor); } return retval.toArray(new AssetField[0]); } finally { getReadLock().unlock(); } }</code><technical_language>Nit: isEmpty explicit size check. suggestion if (retval.isEmpty()) {</technical_language>

Target:
public AssetField[] getAssetFieldsForAddress(final InetAddress address, final String vendor) { getReadLock().lock(); try { if (vendor == null) { LOG.debug("getAssetFieldsForAddress: WSMAN vendor field was null for address {}, returning empty list", InetAddressUtils.str(address)); return new AssetField[0]; } final List<AssetField> retval = new ArrayList<>(); for (final org.opennms.netmgt.config.wsmanAsset.adapter.Package pkg : m_config.getPackages()) { final String pkgVendor = pkg.getVendor(); if (pkgVendor != null) { if (pkgVendor.equals(vendor)) { retval.addAll(pkg.getAssetFields()); } } } if (retval.isEmpty()) { LOG.debug("getAssetFieldsForAddress: Zero AssetField matches returned for with vendor: {}", InetAddressUtils.str(address), vendor); } return retval.toArray(new AssetField[0]); } finally { getReadLock().unlock(); } }
Source:
<code>private void addAcceptor(final Issue issue, IssueResolutionAcceptor acceptor, String validDomain) { acceptor.accept(issue, validDomain, null, null, new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { if (element instanceof GeneratorEntry) { EObject elementRef = ((GeneratorEntry) element).getElementRef(); if (elementRef instanceof Statechart) { TransactionalEditingDomain sharedDomain = DiagramPartitioningUtil.getSharedDomain(); AbstractTransactionalCommand refactoringCommand = new AbstractTransactionalCommand(sharedDomain, CHANGE_DOMAIN_COMMAND, Collections.EMPTY_LIST) { @Override protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { try { <START> Statechart realStatechart = (Statechart) DiagramPartitioningUtil.getSharedDomain() <END> .getResourceSet().getEObject(EcoreUtil.getURI(elementRef), true); (realStatechart).setDomainID(validDomain); } catch (Exception ex) { return CommandResult.newErrorCommandResult(ex); } return CommandResult.newOKCommandResult(); } @Override protected IStatus doUndo(IProgressMonitor monitor, IAdaptable info) throws ExecutionException { return Status.CANCEL_STATUS; } }; try { refactoringCommand.execute(new NullProgressMonitor(), null); } catch (Exception ex) { ex.printStackTrace(); } } } } }); }</code><technical_language>is "unreal" statechart</technical_language>

Target:
private void addAcceptor(final Issue issue, IssueResolutionAcceptor acceptor, String validDomain) { acceptor.accept(issue, validDomain, null, null, new ISemanticModification() { @Override public void apply(EObject element, IModificationContext context) throws Exception { if (element instanceof GeneratorEntry) { EObject referencedStatechart = ((GeneratorEntry) element).getElementRef(); if (referencedStatechart instanceof Statechart) { TransactionalEditingDomain sharedDomain = DiagramPartitioningUtil.getSharedDomain(); DomainChangeCommand refactoringCommand = new DomainChangeCommand(sharedDomain, CHANGE_DOMAIN_COMMAND, Collections.EMPTY_LIST, validDomain, (Statechart) referencedStatechart); try { refactoringCommand.execute(new NullProgressMonitor(), null); } catch (Exception ex) { ex.printStackTrace(); } } } } }); }
Source:
<code>public PlanGroupReduceOperator(GroupReduceFunction<IN, OUT> udf, int[] logicalGroupingFields, String name, TypeInformation<IN> inputType, TypeInformation<OUT> outputType) { super(udf, logicalGroupingFields, name); this.inType = inputType; this.outType = outputType; <START> super.setCombinable(this.isCombinable()); <END> }</code><technical_language>call getUserCodeWrapper().getUserCodeAnnotation(Combinable.class) != null instead of this.isCombinable() need override isCombinable() in PlanUnwrappingReduceGroupOperator</technical_language>

Target:
public PlanGroupReduceOperator(GroupReduceFunction<IN, OUT> udf, int[] logicalGroupingFields, String name, TypeInformation<IN> inputType, TypeInformation<OUT> outputType) { super(udf, logicalGroupingFields, name); this.inType = inputType; this.outType = outputType; super.setCombinable(getUserCodeWrapper().getUserCodeAnnotation(Combinable.class) != null); }
Source:
<code>public static String getString(Locale language, String key) { if ((Objects.isNull(commonMessages) || commonMessages.size() <= 1) && (Objects.isNull(errorMessages) || errorMessages.size() <= 1)) { loadMsgs(); } if (localMessages.containsKey(language)) { ResourceBundle languageLocal = localMessages.get(language); if (languageLocal.containsKey(key)) { return languageLocal.getString(key); } String lowKey = key.toLowerCase(); if (languageLocal.containsKey(lowKey)) { return languageLocal.getString(lowKey); } } try { if (commonMessages.containsKey(language)) { ResourceBundle messages = commonMessages.get(language); if (messages.containsKey(key)) { return messages.getString(key); } } if (errorMessages.containsKey(language)) { ResourceBundle messages = errorMessages.get(language); <START> if (messages.containsKey(key)) { <END> return messages.getString(key); } } return key; } catch (RuntimeException irrelevant) { return key; } }</code><technical_language>put this out of brackets avoid duplicated code</technical_language>

Target:
public static String getString(Locale language, String key) { if ((Objects.isNull(commonMessages) || commonMessages.size() <= 1) && (Objects.isNull(errorMessages) || errorMessages.size() <= 1)) { loadMsgs(); } List<Map<Locale, ResourceBundle>> messages = new ArrayList<>(); messages.add(localMessages); messages.add(commonMessages); messages.add(errorMessages); for (Map<Locale, ResourceBundle> message : messages) { if (message.containsKey(language)) { String foundMessage = getTranslatedMessage(message, language, key); if (!Objects.equals(foundMessage, "")) { return foundMessage; } } } return key; }
Source:
<code>public Iterator<T> iterator() { <START> return Stream.range(0, getWordsNum() << ADDRESS_BITS_PER_WORD) <END> .filter(i -> (getWord(i >> ADDRESS_BITS_PER_WORD) & (1L << i)) != 0) .map(fromInt) .iterator(); }</code><technical_language>hmmm, this seams linear number of elements, existing ones. this is essential method, return a custom Iterator Long.highestOneBit find next bit in constant time for a block jump unset blocks values[i] != 0 something? linear, a lot faster :/</technical_language>

Target:
public Iterator<T> iterator() { return new BitSetIterator<>(this); }
Source:
<code>public ReadSupport<T> getReadSupport(Configuration configuration){ if (readSupportClass != null) { return getReadSupportInstance(readSupportClass); } else { return getReadSupportInstance(configuration); <START> } <END> }</code><technical_language>about: return getReadSupportInstance(readSupportClass == null ? getReadSupportClass(configuration) : readSupportClass)</technical_language>

Target:
ReadSupport<T> getReadSupport(Configuration configuration){ return getReadSupportInstance(readSupportClass == null ? (Class<? extends ReadSupport<T>>) getReadSupportClass(configuration) : readSupportClass); }
Source:
<code>public AbstractBigtableAdmin( BigtableOptions options, Configuration configuration, AbstractBigtableConnection connection, BigtableTableAdminClient bigtableTableAdminClient, Set<TableName> disabledTables) { LOG.debug("Creating BigtableAdmin"); this.configuration = configuration; this.options = options; this.connection = connection; this.bigtableTableAdminClient = bigtableTableAdminClient; this.disabledTables = disabledTables; <START> this.bigtableClusterName = BigtableClusterName.from(options); <END> this.tableAdapter = new TableAdapter(options, columnDescriptorAdapter); }</code><technical_language>nit: cluster name options, is inmutable configuration parameter. created options is created avoid "from" method indirection</technical_language>

Target:
public AbstractBigtableAdmin( BigtableOptions options, Configuration configuration, AbstractBigtableConnection connection, BigtableTableAdminClient bigtableTableAdminClient, Set<TableName> disabledTables) { LOG.debug("Creating BigtableAdmin"); this.configuration = configuration; this.options = options; this.connection = connection; this.bigtableTableAdminClient = bigtableTableAdminClient; this.disabledTables = disabledTables; this.bigtableClusterName = options.getClusterName(); this.tableAdapter = new TableAdapter(options, columnDescriptorAdapter); }
Source:
<code>protected SSLEngine engineCreateSSLEngine(String host, int port) throws IllegalStateException { try { if (dynamicSSLContextImpl == null) { return this.getConfiguredDefaultSSLContext().createSSLEngine(host, port); } SSLContext sslContext = dynamicSSLContextImpl .getSSLContext(new URI(null, null, host, port, null, null, null)); if (sslContext == null) { throw new IllegalStateException(ElytronMessages.log.receivedSSLContextFromDynamicSSLContextProviderWasNull()); } if (sslContext instanceof DynamicSSLContext && sslContext.getSocketFactory().equals(this.engineGetSocketFactory())) { <START> throw new IllegalStateException(ElytronMessages.log.dynamicSSLContextCreatesLoop()); <END> } return sslContext.createSSLEngine(host, port); } catch (URISyntaxException e) { throw new IllegalStateException(ElytronMessages.log.couldNotCreateURI()); } catch (DynamicSSLContextException e) { throw new IllegalStateException(ElytronMessages.log.couldNotCreateDynamicSSLContextEngine()); } }</code><technical_language>this simplified throw ElytronMessages.log.dynamicSSLContextCreatesLoop()</technical_language>

Target:
protected SSLEngine engineCreateSSLEngine(String host, int port) throws IllegalStateException { try { if (dynamicSSLContextImpl == null) { return this.getConfiguredDefaultSSLContext().createSSLEngine(host, port); } SSLContext sslContext = dynamicSSLContextImpl .getSSLContext(new URI(null, null, host, port, null, null, null)); if (sslContext == null) { throw ElytronMessages.log.receivedSSLContextFromDynamicSSLContextProviderWasNull(); } if (sslContext instanceof DynamicSSLContext && sslContext.getSocketFactory().equals(this.engineGetSocketFactory())) { throw ElytronMessages.log.dynamicSSLContextCreatesLoop(); } return sslContext.createSSLEngine(host, port); } catch (URISyntaxException e) { throw ElytronMessages.log.couldNotCreateURI(); } catch (DynamicSSLContextException e) { throw ElytronMessages.log.couldNotCreateDynamicSSLContextEngine(); } }
Source:
<code><START> public void handlesLastPartitionCorrectly() <END> { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = ParallelIndexSupervisorTask.createMergeIOConfigs( 10, createPartitionToLocations(count), CREATE_PARTIAL_SEGMENT_MERGE_IO_CONFIG ); assertNoMissingPartitions(count, assignedPartitionLocation); }</code><technical_language>Some ideas for other assertions. 1) Verify split is evenly distributed. i.e. 10 tasks 2 (for 20), 4 tasks 3 6 tasks 2 (for 24), etc</technical_language>

Target:
public void handlesLastPartitionCorrectly() { List<PartialHashSegmentMergeIOConfig> assignedPartitionLocation = createMergeIOConfigs(); assertNoMissingPartitions(count, assignedPartitionLocation); }
Source:
<code>public static void handleError(ChannelHandlerContext ctx, ProtocolError protocolError) { ChannelFuture f = ctx.writeAndFlush(new ErrorMessage( <START> protocolError.getId(), <END> protocolError.getErrorType(), protocolError.getTrace(), protocolError.getErrorMessage() )); switch (protocolError.getErrorType()) { case Invalid: case Timeout: case Cancelled: case Busy: case Declined: case UnexpectedError: case BadRequest: case NetworkError: case Unhealthy: break; case FatalProtocolError: f.addListener(ChannelFutureListener.CLOSE); break; default: break; } }</code><technical_language>Nit: write a method in ErrorMessage, ProtocolError argument</technical_language>

Target:
public static void handleError(ChannelHandlerContext ctx, ProtocolError protocolError) { ChannelFuture f = ctx.writeAndFlush(new ErrorMessage( protocolError.getId(), protocolError.getErrorType(), protocolError.getTrace(), protocolError.getMessage() )); switch (protocolError.getErrorType()) { case Invalid: case Timeout: case Cancelled: case Busy: case Declined: case UnexpectedError: case BadRequest: case NetworkError: case Unhealthy: break; case FatalProtocolError: f.addListener(ChannelFutureListener.CLOSE); break; default: break; } }