auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { try { DropPartitionMessage msg = deserializer.getDropPartitionMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecs = ReplUtils.genPartSpecs(new Table(msg.getTableObj()), msg.getPartitions()); if (partSpecs.size() > 0) { DropTableDesc dropPtnDesc = new DropTableDesc(actualDbName + "." + actualTblName, partSpecs, null, true, context.eventOnlyReplicationSpec()); Task<DDLWork> dropPtnTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, dropPtnDesc), context.hiveConf ); context.log.debug("Added drop ptn task : {}:{},{}", dropPtnTask.getId(), dropPtnDesc.getTableName(), msg.getPartitions()); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, actualTblName, null); return Collections.singletonList(ReplUtils.appendOpenTxnTaskForMigration(actualDbName, actualTblName, <START> context.hiveConf, updatedMetadata, dropPtnTask, msg.getTableObj())); <END> } else { throw new SemanticException( "DROP PARTITION EVENT does not return any part descs for event message :" + context.dmd.getPayload()); } } catch (Exception e) { throw (e instanceof SemanticException) ? (SemanticException) e : new SemanticException("Error reading message members", e); } }</code><technical_language>msg.getTableObj() deserialisation this method is called in this method is expensive. store in local variable. Check for other Handlers too</technical_language>

Target:
public List<Task<? extends Serializable>> handle(Context context) throws SemanticException { try { DropPartitionMessage msg = deserializer.getDropPartitionMessage(context.dmd.getPayload()); String actualDbName = context.isDbNameEmpty() ? msg.getDB() : context.dbName; String actualTblName = context.isTableNameEmpty() ? msg.getTable() : context.tableName; Map<Integer, List<ExprNodeGenericFuncDesc>> partSpecs = ReplUtils.genPartSpecs(new Table(msg.getTableObj()), msg.getPartitions()); if (partSpecs.size() > 0) { DropTableDesc dropPtnDesc = new DropTableDesc(actualDbName + "." + actualTblName, partSpecs, null, true, context.eventOnlyReplicationSpec()); Task<DDLWork> dropPtnTask = TaskFactory.get( new DDLWork(readEntitySet, writeEntitySet, dropPtnDesc), context.hiveConf ); context.log.debug("Added drop ptn task : {}:{},{}", dropPtnTask.getId(), dropPtnDesc.getTableName(), msg.getPartitions()); updatedMetadata.set(context.dmd.getEventTo().toString(), actualDbName, actualTblName, null); return Collections.singletonList(dropPtnTask); } else { throw new SemanticException( "DROP PARTITION EVENT does not return any part descs for event message :" + context.dmd.getPayload()); } } catch (Exception e) { throw (e instanceof SemanticException) ? (SemanticException) e : new SemanticException("Error reading message members", e); } }
Source:
<code>public int compare(Viewer viewer, Object e1, Object e2) { int rc = 0; <START> rc = super.compare(viewer, ((Ref) e1).getName(), ((Ref) e2).getName()); <END> if (direction == DESCENDING) { rc = -rc; } return rc; }</code><technical_language>This sorts ref name, of column is clicked shown sorted in UI. This is confusing. sort based current column</technical_language>

Target:
public int compare(Viewer viewer, Object e1, Object e2) { int rc = 0; if (direction == DESCENDING) { rc = super.compare(viewer, labelProvider.getText(e1), labelProvider.getText(e2)); } else { rc = super.compare(viewer, labelProvider.getText(e2), labelProvider.getText(e1)); } return rc; }
Source:
<code>public void execute(int iterationId) { try { Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(getVdss().get(iterationId), getStoragePool(), masterStorageDomainId, storagePoolIsoMap, true)); StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), getVdss().get(iterationId).getId()); } catch (RuntimeException e) { <START> log.error("Failed to connect/refresh storagePool. Host '{}' to storage pool '{}'. Error: {}", <END> getVdss().get(iterationId).getName(), getStoragePool().getName(), e.getMessage()); log.debug("Exception", e); } }</code><technical_language>s/. Error//</technical_language>

Target:
public void execute(int iterationId) { try { Backend.getInstance().getResourceManager().RunVdsCommand( VDSCommandType.ConnectStoragePool, new ConnectStoragePoolVDSCommandParameters(getVdss().get(iterationId), getStoragePool(), masterStorageDomainId, storagePoolIsoMap, true)); StorageHelperDirector.getInstance().getItem(getStorageDomain().getStorageType()) .disconnectStorageFromDomainByVdsId(getStorageDomain(), getVdss().get(iterationId).getId()); } catch (RuntimeException e) { log.error("Failed to connect/refresh storagePool. Host '{}' to storage pool '{}': {}", getVdss().get(iterationId).getName(), getStoragePool().getName(), e.getMessage()); log.debug("Exception", e); } }
Source:
<code>public void run() { FedoraTransaction tx = txManager.startTransaction(); try (Timer.Context context = timer.time()) { for (PID pid : objsToDestroy) { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(pid); assertCanDestroy(agent, repoObj, aclService); if (!inheritedAclFactory.isMarkedForDeletion(pid)) { log.warn("Skipping destruction of {}, it is not marked for deletion", pid); continue; } if (!repoObj.getResource().hasProperty(RDF.type, Cdr.Tombstone)) { RepositoryObject parentObj = repoObj.getParent(); destroyTree(repoObj); parentObj.getPremisLog().buildEvent(Premis.Deletion) .addAuthorizingAgent(agent.getUsername()) .addOutcome(true) .addEventDetail("{0} object(s) were destroyed", deletedObjCount) <START> .addEventDetail("Objects destroyed: {0}", <END> String.join(System.getProperty("line.separator"), deletedObjIds)) .writeAndClose(); } indexingMessageSender.sendIndexingOperation(agent.getUsername(), pid, DELETE_SOLR_TREE); } } catch (Exception e) { tx.cancel(e); } finally { tx.close(); } destroyBinaries(); }</code><technical_language>a newline colon ids line</technical_language>

Target:
public void run() { FedoraTransaction tx = txManager.startTransaction(); try (Timer.Context context = timer.time()) { for (PID pid : objsToDestroy) { RepositoryObject repoObj = repoObjLoader.getRepositoryObject(pid); assertCanDestroy(agent, repoObj, aclService); if (!inheritedAclFactory.isMarkedForDeletion(pid)) { log.warn("Skipping destruction of {}, it is not marked for deletion", pid); continue; } if (!repoObj.getResource().hasProperty(RDF.type, Cdr.Tombstone)) { RepositoryObject parentObj = repoObj.getParent(); deletedObjIds.add(repoObj.getPid().getUUID()); destroyTree(repoObj); String lineSeparator = System.getProperty("line.separator"); parentObj.getPremisLog().buildEvent(Premis.Deletion) .addAuthorizingAgent(agent.getUsername()) .addOutcome(true) .addEventDetail("{0} object(s) were destroyed", deletedObjIds.size()) .addEventDetail("Objects destroyed:" + lineSeparator + "{0}", String.join(lineSeparator, deletedObjIds)) .writeAndClose(); } indexingMessageSender.sendIndexingOperation(agent.getUsername(), pid, DELETE_SOLR_TREE); } } catch (Exception e) { tx.cancel(e); } finally { tx.close(); } destroyBinaries(); }
Source:
<code>private void setupRegistrationForm() { try { InputStream in = getAssets().open("config/registration_form.json"); Gson gson = new Gson(); RegistrationForm form = gson.fromJson(new InputStreamReader(in), RegistrationForm.class); LayoutInflater inflater = getLayoutInflater(); for (RegistrationFormField field : form.getFields()) { IRegistrationFieldView fieldView = null; <START> if (field.getFieldType().equalsIgnoreCase(RegistrationFieldType.EMAIL.toString()) <END> || field.getFieldType().equalsIgnoreCase(RegistrationFieldType.PASSWORD.toString()) || field.getFieldType().equalsIgnoreCase(RegistrationFieldType.TEXT.toString())) { View view = inflater.inflate(R.layout.view_register_edit_text, null); fieldView = new RegistrationEditTextView(field, view); } else if (field.getFieldType().equalsIgnoreCase(RegistrationFieldType.TEXTAREA.toString())) { View view = inflater.inflate(R.layout.view_register_text_area, null); fieldView = new RegistrationTextAreaView(field, view); } else if (field.getFieldType().equalsIgnoreCase(RegistrationFieldType.MULTI.toString())) { View view = inflater.inflate(R.layout.view_register_spinner, null); fieldView = new RegistrationSpinnerView(field, view); } if (fieldView != null) mFieldViews.add(fieldView); } for (IRegistrationFieldView v : mFieldViews) { if (v.getField().isRequired()) { requiredFieldsLayout.addView(v.getView()); } else { optionalFieldsLayout.addView(v.getView()); } } requiredFieldsLayout.requestLayout(); optionalFieldsLayout.requestLayout(); } catch(Exception ex) { logger.error(ex); } }</code><technical_language>This simplified a bit if enum more above</technical_language>

Target:
private void setupRegistrationForm() { try { RegistrationDescription form = new Api(this).getRegistrationDescription(); LayoutInflater inflater = getLayoutInflater(); for (RegistrationFormField field : form.getFields()) { IRegistrationFieldView fieldView = IRegistrationFieldView.Factory.getInstance(inflater, field); if (fieldView != null) mFieldViews.add(fieldView); } for (IRegistrationFieldView v : mFieldViews) { if (v.getField().isRequired()) { requiredFieldsLayout.addView(v.getView()); } else { optionalFieldsLayout.addView(v.getView()); } } requiredFieldsLayout.requestLayout(); optionalFieldsLayout.requestLayout(); } catch(Exception ex) { logger.error(ex); } }
Source:
<code>public void start() { super.start(); logger.info("Starting SparkDriver"); SparkStreamingSupport processor; Properties sparkConfigs = null; try { processor = getComponent(SparkStreamingSupport.class); <START> if (processor != null) { <END> sparkConfigs = getSparkModuleProperties(processor); } } catch (NoSuchBeanDefinitionException e) { throw new RuntimeException("Either java or scala module should be present."); } startSparkStreamingContext(sparkConfigs, processor); }</code><technical_language>Do need Assert.notNull well</technical_language>

Target:
public void start() { super.start(); logger.info("Starting SparkDriver"); SparkStreamingSupport processor; Properties sparkConfigs = null; try { processor = getComponent(SparkStreamingSupport.class); Assert.notNull(processor, "Problem getting the spark streaming module. Is the module context active?"); sparkConfigs = getSparkModuleProperties(processor); } catch (NoSuchBeanDefinitionException e) { throw new IllegalStateException("Either java or scala module should be present."); } startSparkStreamingContext(sparkConfigs, processor); }
Source:
<code>public String getApiUri(DateTime startDate, FilterBuilder filterBuilder, String search, String after, int limit) throws IOException { Map<String, String> params = new HashMap<String, String>(); <START> params.put(START_DATE, Utils.convertDateTimeToString(startDate)); <END> params.put(LIMIT, Integer.toString(limit)); if (filterBuilder != null) { params.put(FILTER, filterBuilder.toString()); } if (search != null) { params.put(SEARCH_QUERY, search); } if (after != null) { params.put(AFTER_CURSOR, after); } return getEncodedPathWithQueryParams("/", params); }</code><technical_language>Do need check if startDate is null here</technical_language>

Target:
public String getApiUri(DateTime startDate, FilterBuilder filterBuilder, String search, String after, int limit) throws IOException { Map<String, String> params = new HashMap<String, String>(); if (startDate != null) { params.put(START_DATE, Utils.convertDateTimeToString(startDate)); } params.put(LIMIT, Integer.toString(limit)); if (filterBuilder != null) { params.put(FILTER, filterBuilder.toString()); } if (search != null) { params.put(SEARCH_QUERY, search); } if (after != null) { params.put(AFTER_CURSOR, after); } return getEncodedPathWithQueryParams("/", params); }
Source:
<code>public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { if (StringUtil.isBlank(identifier)) { return Optional.empty(); } this.ensureThatIsbnIsValid(identifier); Document html; try { html = Jsoup.connect(BASE_URL + identifier + "/bibtex").userAgent(URLDownload.USER_AGENT).get(); } catch (IOException e) { throw new FetcherException("Could not ", e); } Element textArea = html.select("textarea").first(); Element potentialErrorMessageDiv = html.select("div#flash-notice.notice.add-bottom").first(); if (potentialErrorMessageDiv.hasText() && potentialErrorMessageDiv.text().contains("No Results")) { <START> LOGGER.error("ISBN " + identifier + " not found at ottobib"); <END> } Optional<BibEntry> entry = Optional.empty(); try { entry = BibtexParser.singleFromString(textArea.text(), importFormatPreferences, new DummyFileUpdateMonitor()); } catch (ParseException e) { throw new FetcherException("An internal parser error occurred", e); } entry.ifPresent(bibEntry -> doPostCleanup(bibEntry)); return entry; }</code><technical_language>suggestion LOGGER.error("ISBN { } ottobib", identifier); This is recommended</technical_language>

Target:
public Optional<BibEntry> performSearchById(String identifier) throws FetcherException { if (StringUtil.isBlank(identifier)) { return Optional.empty(); } this.ensureThatIsbnIsValid(identifier); Document html; try { html = Jsoup.connect(BASE_URL + identifier + "/bibtex").userAgent(URLDownload.USER_AGENT).get(); } catch (IOException e) { throw new FetcherException("Could not ", e); } Element textArea = html.select("textarea").first(); Optional<Element> potentialErrorMessageDiv = Optional.ofNullable((html.select("div#flash-notice.notice.add-bottom").first())); if (potentialErrorMessageDiv.isPresent() && potentialErrorMessageDiv.get().text().contains("No Results")) { LOGGER.error("ISBN not found at ottobib", identifier); } Optional<BibEntry> entry = Optional.empty(); try { entry = BibtexParser.singleFromString(textArea.text(), importFormatPreferences, new DummyFileUpdateMonitor()); } catch (ParseException e) { throw new FetcherException("An internal parser error occurred", e); } entry.ifPresent(bibEntry -> doPostCleanup(bibEntry)); return entry; }
Source:
<code><START> long getWatermark(SystemStream systemStream) { <END> return watermarks.get(systemStream); }</code><technical_language>nit: null-safety well. private / invocation context argument exist in map object watermarks</technical_language>

Target:
long getWatermark(SystemStream systemStream) { return watermarkStates.entrySet().stream() .filter(entry -> entry.getKey().getSystemStream().equals(systemStream)) .map(entry -> entry.getValue().getWatermarkTime()) .min(Long::compare) .orElse(WATERMARK_NOT_EXIST); }
Source:
<code>public void getArtifact() throws Exception { respondWith(JSON_GET_ARTIFACT); ToscaTemplatesArtifact toscaTemplatesArtifact = osv3().artifact().toscaTemplatesArtifact().get(ARTIFACT_ID); <START> server.takeRequest(); <END> assertEquals(toscaTemplatesArtifact.getName(), "test.zip"); assertEquals(toscaTemplatesArtifact.getStatus(), "active"); }</code><technical_language>Minor: this work server.takeRequest();? (Also in other tests)</technical_language>

Target:
public void getArtifact() throws Exception { respondWith(JSON_GET_ARTIFACT); ToscaTemplatesArtifact toscaTemplatesArtifact = osv3().artifact().toscaTemplatesArtifact().get(ARTIFACT_ID); assertEquals(toscaTemplatesArtifact.getName(), "test.zip"); assertEquals(toscaTemplatesArtifact.getStatus(), "active"); }
Source:
<code>public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { <START> PlayerList players = game.getState().getPlayerList(controller.getId()); <END> for (UUID playerId : players) { Player player = game.getPlayer(playerId); if (player != null) { int landCount = game.getBattlefield().countAll(new FilterControlledLandPermanent(), player.getId(), game); if (landCount > 5) { TargetControlledPermanent target = new TargetControlledPermanent(5, 5, new FilterControlledLandPermanent("lands to keep"), true); if (target.choose(Outcome.Sacrifice, player.getId(), source.getSourceId(), game)) { for (Permanent permanent : game.getBattlefield().getActivePermanents(new FilterControlledLandPermanent(), player.getId(), source.getSourceId(), game)) { if (permanent != null && !target.getTargets().contains(permanent.getId())) { permanent.sacrifice(source.getId(), game); } } } } else if (landCount < 5) { FilterLandPermanent filter = new FilterLandPermanent(); filter.add(new ControllerPredicate(TargetController.YOU)); int amount = 5 - landCount; TargetCardInLibrary target = new TargetCardInLibrary(0, amount, new FilterBasicLandCard()); if (player.searchLibrary(target, game)) { player.moveCards(new CardsImpl(target.getTargets()).getCards(game), Zone.BATTLEFIELD, source, game, true, false, false, null); } player.shuffleLibrary(source, game); } } } return true; } return false; }</code><technical_language>getPlayersInRange get affected players players table</technical_language>

Target:
public boolean apply(Game game, Ability source) { Player controller = game.getPlayer(source.getControllerId()); if (controller != null) { PlayerList players = game.getState().getPlayersInRange(controller.getId(),game); for (UUID playerId : players) { Player player = game.getPlayer(playerId); if (player != null) { int landCount = game.getBattlefield().countAll(new FilterControlledLandPermanent(), player.getId(), game); if (landCount > 5) { TargetControlledPermanent target = new TargetControlledPermanent(5, 5, new FilterControlledLandPermanent("lands to keep"), true); if (target.choose(Outcome.Sacrifice, player.getId(), source.getSourceId(), game)) { for (Permanent permanent : game.getBattlefield().getActivePermanents(new FilterControlledLandPermanent(), player.getId(), source.getSourceId(), game)) { if (permanent != null && !target.getTargets().contains(permanent.getId())) { permanent.sacrifice(source.getId(), game); } } } } else if (landCount < 5) { FilterLandPermanent filter = new FilterLandPermanent(); filter.add(new ControllerPredicate(TargetController.YOU)); int amount = 5 - landCount; TargetCardInLibrary target = new TargetCardInLibrary(0, amount, new FilterBasicLandCard()); if (player.searchLibrary(target, game)) { player.moveCards(new CardsImpl(target.getTargets()).getCards(game), Zone.BATTLEFIELD, source, game, true, false, false, null); } player.shuffleLibrary(source, game); } } } return true; } return false; }
Source:
<code>public void setProperty(JMeterProperty property) { if (!(property instanceof StringProperty)) { super.setProperty(property); return; } final String propName = property.getName(); if (!"shareMode".equals(propName)) { super.setProperty(property); return; } final String propValue = property.getStringValue(); if (!propValue.contains(" ")) { super.setProperty(property); return; } try { ResourceBundle rb = (ResourceBundle) Introspector .getBeanInfo(this.getClass()) .getBeanDescriptor() .getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); Optional<String> first = Arrays.stream(CSVDataSetBeanInfo.getShareTags()) <START> .filter(resKey -> propValue.equals(rb.getString(resKey))) <END> .findFirst(); if (first.isPresent()) { ((StringProperty) property).setValue(first.get()); } else { log.warn("Could not translate {}={} using Locale: {}", propName, propValue, rb.getLocale()); } } catch (IntrospectionException e) { log.error("Could not find BeanInfo; cannot translate shareMode entries", e); } super.setProperty(property); }</code><technical_language>more readable extract rb.getString(resKey) a map step filtering? .map(rb::getString) .filter(propValue::equals)</technical_language>

Target:
public void setProperty(JMeterProperty property) { if (!(property instanceof StringProperty)) { super.setProperty(property); return; } final String propName = property.getName(); if (!"shareMode".equals(propName)) { super.setProperty(property); return; } final String propValue = property.getStringValue(); if (propValue.contains(" ")) { try { final BeanInfo beanInfo = Introspector.getBeanInfo(this.getClass()); final ResourceBundle rb = (ResourceBundle) beanInfo.getBeanDescriptor().getValue(GenericTestBeanCustomizer.RESOURCE_BUNDLE); for (String resKey : CSVDataSetBeanInfo.getShareTags()) { if (propValue.equals(rb.getString(resKey))) { if (log.isDebugEnabled()) { log.debug("Converted {}={} to using Locale: {}", propName, propValue, resKey, rb.getLocale()); } ((StringProperty) property).setValue(resKey); super.setProperty(property); return; } } log.warn("Could not translate {}={} using Locale: {}", propName, propValue, rb.getLocale()); } catch (IntrospectionException e) { log.error("Could not find BeanInfo; cannot translate shareMode entries", e); } } super.setProperty(property); }
Source:
<code>public void emptyPartitionOverrideTest() throws Exception { <START> if (overrideEnabled) { <END> metricRegistry = new MetricRegistry(); ClusterMap clusterManagerWithEmptyRecord = new HelixClusterManager(clusterMapConfig, hostname, new MockHelixManagerFactory(helixCluster, null, null), metricRegistry); Set<String> writableInClusterManager = new HashSet<>(); for (PartitionId partition : clusterManagerWithEmptyRecord.getWritablePartitionIds(null)) { String partitionStr = useComposite ? ((Partition) partition).toPathString() : ((AmbryPartition) partition).toPathString(); writableInClusterManager.add(partitionStr); } Set<String> writableInCluster = helixCluster.getWritablePartitions(); if (writableInCluster.isEmpty()) { writableInCluster = helixCluster.getAllWritablePartitions(); } assertEquals("Mismatch in writable partitions during initialization", writableInCluster, writableInClusterManager); } }</code><technical_language>assumeTrue in a couple other places</technical_language>

Target:
public void emptyPartitionOverrideTest() throws Exception { assumeTrue(overrideEnabled); metricRegistry = new MetricRegistry(); ClusterMap clusterManagerWithEmptyRecord = new HelixClusterManager(clusterMapConfig, hostname, new MockHelixManagerFactory(helixCluster, null, null), metricRegistry); Set<String> writableInClusterManager = new HashSet<>(); for (PartitionId partition : clusterManagerWithEmptyRecord.getWritablePartitionIds(null)) { String partitionStr = useComposite ? ((Partition) partition).toPathString() : ((AmbryPartition) partition).toPathString(); writableInClusterManager.add(partitionStr); } Set<String> writableInCluster = helixCluster.getWritablePartitions(); if (writableInCluster.isEmpty()) { writableInCluster = helixCluster.getAllWritablePartitions(); } assertEquals("Mismatch in writable partitions during initialization", writableInCluster, writableInClusterManager); }
Source:
<code>public static void startKafkaStreamsAndWaitForRunningState(final KafkaStreams kafkaStreams, final long timeoutMs) { final CountDownLatch countDownLatch = new CountDownLatch(1); kafkaStreams.setStateListener((newState, oldState) -> { if (newState == KafkaStreams.State.RUNNING) { countDownLatch.countDown(); } }); kafkaStreams.start(); try { countDownLatch.await(timeoutMs, TimeUnit.MILLISECONDS); } catch (final InterruptedException interruptedException) { <START> throw new AssertionError("KafkaStreams did not transit to RUNNING state within " + timeoutMs + " milli seconds."); <END> } }</code><technical_language>error message is accurate wait for timeoutMs, interrupted is wait less. expect interrupt rethrowing easiest handle this</technical_language>

Target:
public static void startKafkaStreamsAndWaitForRunningState(final KafkaStreams kafkaStreams, final long timeoutMs) throws InterruptedException { final CountDownLatch countDownLatch = new CountDownLatch(1); kafkaStreams.setStateListener((newState, oldState) -> { if (newState == KafkaStreams.State.RUNNING) { countDownLatch.countDown(); } }); kafkaStreams.start(); assertThat( "KafkaStreams did not transit to RUNNING state within " + timeoutMs + " milli seconds.", countDownLatch.await(timeoutMs, TimeUnit.MILLISECONDS), equalTo(true)); }
Source:
<code>private JsonObject parseStringToJson(String string) { InputStream inputStream = new ByteArrayInputStream(string.getBytes(StandardCharsets.UTF_8)); <START> JsonReader jsonReader = Json.createReader(inputStream); <END> JsonObject parsedObject = jsonReader.readObject(); jsonReader.close(); return parsedObject; }</code><technical_language>a StringReader instead of a ByteArrayInputStream here</technical_language>

Target:
private JsonObject parseStringToJson(String string) { StringReader reader = new StringReader(string); JsonReader jsonReader = Json.createReader(reader); JsonObject parsedObject = jsonReader.readObject(); jsonReader.close(); return parsedObject; }
Source:
<code>@Override public String getUnderFSType() { <START> LOG.debug("getUnderFSType"); <END> return "b2"; }</code><technical_language>Enabling debug logging UnderFileSystemWithLogging class negate need for types of log messages</technical_language>

Target:
public String getUnderFSType() { return "b2"; }
Source:
<code>private GoogleCloudStorageDivolteFile(final String fileName) throws IOException { this.buffer = new AvroRecordBuffer[recordBufferSize]; this.inflightName = inflightDir + GCS_PATH_SEPARATOR_CHAR + fileName; this.inflightPartialName = inflightName + PART_CLASSIFIER; this.inflightNameEncoded = URLEncoder.encode(inflightName, URL_ENCODING); this.inflightPartialNameEncoded = inflightNameEncoded + PART_CLASSIFIER; this.publishNameEncoded = URLEncoder.encode(publishDir + GCS_PATH_SEPARATOR_CHAR + fileName, URL_ENCODING); final URL remoteFileUrl = uploadUrlFor(bucketEncoded, inflightNameEncoded); final HttpURLConnection connection = setupUrlConnection(POST, remoteFileUrl, true, AVRO_CONTENT_TYPE_HEADER); final OutputStream os = connection.getOutputStream(); avroTargetStream = new DynamicDelegatingOutputStream(); avroTargetStream.attachDelegate(os); writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<>(schema)).create(schema, avroTargetStream); writer.flush(); avroTargetStream.detachDelegate(); os.flush(); <START> os.close(); <END> final GcsObjectResponse response = parseResponse(GcsObjectResponse.class, connection); logger.debug("Google Cloud Storage upload response {}", response); partWritten = false; }</code><technical_language>closing includes flushing, I thought? (And detaching flushed it.)</technical_language>

Target:
private GoogleCloudStorageDivolteFile(final String fileName) throws IOException { this.buffer = new AvroRecordBuffer[recordBufferSize]; this.inflightName = inflightDir + GCS_PATH_SEPARATOR_CHAR + fileName; this.inflightPartialName = inflightName + PART_CLASSIFIER; this.inflightNameEncoded = URLEncoder.encode(inflightName, URL_ENCODING); this.inflightPartialNameEncoded = inflightNameEncoded + PART_CLASSIFIER; this.publishNameEncoded = URLEncoder.encode(publishDir + GCS_PATH_SEPARATOR_CHAR + fileName, URL_ENCODING); final URL remoteFileUrl = uploadUrlFor(bucketEncoded, inflightNameEncoded); final HttpURLConnection connection = setupUrlConnection(POST, remoteFileUrl, true, AVRO_CONTENT_TYPE_HEADER); final OutputStream os = connection.getOutputStream(); avroTargetStream = new DynamicDelegatingOutputStream(); avroTargetStream.attachDelegate(os); try { writer = new DataFileWriter<GenericRecord>(new GenericDatumWriter<>(schema)).create(schema, avroTargetStream); writer.flush(); } finally { avroTargetStream.detachDelegate(); } os.close(); final GcsObjectResponse response = parseResponse(GcsObjectResponse.class, connection); logger.debug("Google Cloud Storage upload response {}", response); partWritten = false; }
Source:
<code>public void testNoReconnectAfterEventSinkClose() throws Exception { List<String> results = new ArrayList<String>(); Client client = new ResteasyClientBuilder().connectionPoolSize(10).build(); WebTarget target = client.target(generateURL("/service/server-sent-events/closeAfterSent")); SseEventSourceImpl sourceImpl = (SseEventSourceImpl)SseEventSource.target(target).build(); sourceImpl.setAlwasyReconnect(false); try (SseEventSource source = sourceImpl) { source.register(event -> results.add(event.readData())); source.open(); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } Assert.assertEquals("Received unexpected events", "[thing1, thing2, thing3]", results.toString()); results.clear(); WebTarget target2 = client.target(generateURL("/service/server-sent-events/closeAfterSent")); SseEventSourceImpl sourceImpl2 = (SseEventSourceImpl)SseEventSource.target(target2).build(); sourceImpl2.setAlwasyReconnect(false); try (SseEventSource source = sourceImpl2) { source.register(event -> results.add(event.readData())); source.open(); Thread.sleep(1000); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } Assert.assertEquals("Received unexpected events", "[thing1, thing2, thing3]", results.toString()); }</code><technical_language>logger pls do switch of e.printStackTrace(); line 495</technical_language>

Target:
public void testNoReconnectAfterEventSinkClose() throws Exception { List<String> results = new ArrayList<String>(); Client client = new ResteasyClientBuilder().connectionPoolSize(10).build(); WebTarget target = client.target(generateURL("/service/server-sent-events/closeAfterSent")); SseEventSourceImpl sourceImpl = (SseEventSourceImpl)SseEventSource.target(target).build(); sourceImpl.setAlwasyReconnect(false); try (SseEventSource source = sourceImpl) { source.register(event -> results.add(event.readData())); source.open(); Thread.sleep(1000); } catch (InterruptedException e) { logger.info("Thread sleep interruped", e); } Assert.assertEquals("Received unexpected events", "[thing1, thing2, thing3]", results.toString()); results.clear(); WebTarget target2 = client.target(generateURL("/service/server-sent-events/closeAfterSent")); SseEventSourceImpl sourceImpl2 = (SseEventSourceImpl)SseEventSource.target(target2).build(); sourceImpl2.setAlwasyReconnect(false); try (SseEventSource source = sourceImpl2) { source.register(event -> results.add(event.readData())); source.open(); Thread.sleep(1000); } catch (InterruptedException e) { logger.info("Thread sleep interruped", e); } Assert.assertEquals("Received unexpected events", "[thing1, thing2, thing3]", results.toString()); }
Source:
<code><START> public RequestBuilder setMergeVariables(Map mergeVariables) throws JsonProcessingException { <END> params.put("merge_variables", objectMapper.writeValueAsString(mergeVariables)); return this; }</code><technical_language>this is a checked exception (not runtime exception) callers need update code catch it. is a breaking API change imo. planning bump major version</technical_language>

Target:
public RequestBuilder setMergeVariables(Map mergeVariables) throws ParsingException { try { params.put("merge_variables", objectMapper.writeValueAsString(mergeVariables)); return this; } catch (JsonProcessingException e) { throw new ParsingException(e); } }
Source:
<code>public IntegrationFlowFunctionSupport(FunctionCatalog functionCatalog, FunctionInspector functionInspector, CompositeMessageConverterFactory messageConverterFactory, FunctionProperties functionProperties) { Assert.notNull(functionCatalog, "'functionCatalog' must not be null"); Assert.notNull(functionInspector, "'functionInspector' must not be null"); <START> Assert.notNull(messageConverterFactory, "'messageConverterFactory' must not be null"); <END> this.functionCatalog = functionCatalog; this.functionInspector = functionInspector; this.messageConverterFactory = messageConverterFactory; this.functionProperties = functionProperties; }</code><technical_language>I Assert.notNull() for functionProperties well</technical_language>

Target:
public IntegrationFlowFunctionSupport(FunctionCatalog functionCatalog, FunctionInspector functionInspector, CompositeMessageConverterFactory messageConverterFactory, FunctionProperties functionProperties) { Assert.notNull(functionCatalog, "'functionCatalog' must not be null"); Assert.notNull(functionInspector, "'functionInspector' must not be null"); Assert.notNull(messageConverterFactory, "'messageConverterFactory' must not be null"); Assert.notNull(functionProperties, "'functionProperties' must not be null"); this.functionCatalog = functionCatalog; this.functionInspector = functionInspector; this.messageConverterFactory = messageConverterFactory; this.functionProperties = functionProperties; }
Source:
<code>public Iterable<Tree> children() { List<Tree> result = new ArrayList<>(); if(openParenToken != null) { result.add(openParenToken); } <START> for (Tree tree : super.children()) { <END> result.add(tree); } if(closeParenToken != null) { result.add(closeParenToken); } return result; }</code><technical_language>super.children().forEach(res::add);</technical_language>

Target:
public Iterable<Tree> children() { List<Tree> result = new ArrayList<>(); if(openParenToken != null) { result.add(openParenToken); } super.children().forEach(result::add); if (closeParenToken != null) { result.add(closeParenToken); } return result; }
Source:
<code>public void init(IWorkbench workbench) { <START> if (!getProfilingType().equals("generic")) { <END> final IPreferenceStore store = new ScopedPreferenceStore( configScopeInstance, getPluginID()); setPreferenceStore(store); } else { setDescription("Profiling Preferences"); } }</code><technical_language>I profiling types public static final Strings (or Objects) defined in a central place</technical_language>

Target:
public void init(IWorkbench workbench) { if (!getProfilingType().equals("generic")) { final IPreferenceStore store = new ScopedPreferenceStore( configScopeInstance, getProfilingType()); setPreferenceStore(store); } else { setDescription("Profiling Preferences"); } }
Source:
<code>public List<Facility> getFacilitiesWhereUserIsAdmin(PerunSession sess, User user) throws InternalErrorException { try { return jdbc.query("select " + facilityMappingSelectQuery + " from facilities " + " left outer join authz on authz.facility_id=facilities.id " + " left outer join groups_members on groups_members.group_id=authz.authorized_group_id " + " left outer join members on members.id=groups_members.member_id " + <START> " where (authz.user_id=? or members.user_id=?) and authz.role_id=(select id from roles where name=?) and authz.facility_id=facilities.id", <END> FACILITY_MAPPER, user.getId(), user.getId(), Role.FACILITYADMIN.getRoleName()); } catch (RuntimeException e) { throw new InternalErrorException(e); } }</code><technical_language>part "authz.facility_id=facilities.id" is in left outer join. I is needed here</technical_language>

Target:
public List<Facility> getFacilitiesWhereUserIsAdmin(PerunSession sess, User user) throws InternalErrorException { try { return jdbc.query("select " + facilityMappingSelectQuery + " from facilities " + " left outer join authz on authz.facility_id=facilities.id " + " left outer join groups_members on groups_members.group_id=authz.authorized_group_id " + " left outer join members on members.id=groups_members.member_id " + " where (authz.user_id=? or members.user_id=?) and authz.role_id=(select id from roles where name=?) ", FACILITY_MAPPER, user.getId(), user.getId(), Role.FACILITYADMIN.getRoleName()); } catch (RuntimeException e) { throw new InternalErrorException(e); } }
Source:
<code>public RunLengthBitPackingHybridEncoder(int bitWidth, int initialCapacity, int pageSize, ByteBufferAllocator allocator) { if (DEBUG) { LOG.debug(String.format("Encoding: RunLengthBitPackingHybridEncoder with " + "bithWidth: %d initialCapacity %d", bitWidth, initialCapacity)); } Preconditions.checkArgument(bitWidth >= 0 && bitWidth <= 32, "bitWidth must be >= 0 and <= 32"); this.bitWidth = bitWidth; <START> this.allocator = allocator; <END> this.baos = new CapacityByteArrayOutputStream(initialCapacity, pageSize, this.allocator); this.packBuffer = new byte[bitWidth]; this.bufferedValues = new int[8]; this.packer = Packer.LITTLE_ENDIAN.newBytePacker(bitWidth); reset(false); }</code><technical_language>unused</technical_language>

Target:
public RunLengthBitPackingHybridEncoder(int bitWidth, int initialCapacity, int pageSize, ByteBufferAllocator allocator) { if (DEBUG) { LOG.debug(String.format("Encoding: RunLengthBitPackingHybridEncoder with " + "bithWidth: %d initialCapacity %d", bitWidth, initialCapacity)); } Preconditions.checkArgument(bitWidth >= 0 && bitWidth <= 32, "bitWidth must be >= 0 and <= 32"); this.bitWidth = bitWidth; this.baos = new CapacityByteArrayOutputStream(initialCapacity, pageSize, allocator); this.packBuffer = new byte[bitWidth]; this.bufferedValues = new int[8]; this.packer = Packer.LITTLE_ENDIAN.newBytePacker(bitWidth); reset(false); }
Source:
<code>public void testNonAdminUserRetrievingDocuments() throws Exception { final String projects = {"multi-tenancy-1", "multi-tenancy-2"}; final String userName = "nonadminuser"; String kibanaIndex = getKibanaIndex(KibanaIndexMode.SHARED_OPS, userName, false); <START> givenDocumentIsIndexed(kibanaIndex, "config", "4.6.4", "myKibanaIndex"); <END> givenUserIsNotClusterAdmin(userName); givenUserIsAdminForProjects(projects); whenGettingDocument(String.format("%s/config/4.6.4", kibanaIndex)); assertThatResponseIsSuccessful(); for (String project : projects) { whenGettingDocument(String.format("%s/_count", formatProjectIndexPattern(project, "uuid"))); assertThatResponseIsSuccessful(); } whenSearchingProjects(projects); assertThatResponseIsSuccessful(); whenGettingDocument(".operations.*/_count"); assertThatResponseIsForbidden(); whenGettingDocument(".kibana/config/4.6.4"); assertThatResponseIsSuccessful(); assertThatMessageEquals("myKibanaIndex"); }</code><technical_language>instead of hardcoding 4.6.4 move a test env var</technical_language>

Target:
public void testNonAdminUserRetrievingDocuments() throws Exception { final String projects = {"multi-tenancy-1", "multi-tenancy-2"}; final String userName = "nonadminuser"; String kibanaIndex = getKibanaIndex(KibanaIndexMode.SHARED_OPS, userName, false); givenDocumentIsIndexed(kibanaIndex, "config", OLD_KIBANA_VERSION, "myKibanaIndex"); givenUserIsNotClusterAdmin(userName); givenUserIsAdminForProjects(projects); whenGettingDocument(String.format("%s/config/%s", kibanaIndex, OLD_KIBANA_VERSION)); assertThatResponseIsSuccessful(); for (String project : projects) { whenGettingDocument(String.format("%s/_count", formatProjectIndexPattern(project, "uuid"))); assertThatResponseIsSuccessful(); } whenSearchingProjects(projects); assertThatResponseIsSuccessful(); whenGettingDocument(".operations.*/_count"); assertThatResponseIsForbidden(); whenGettingDocument(".kibana/config/" + OLD_KIBANA_VERSION); assertThatResponseIsSuccessful(); assertThatMessageEquals("myKibanaIndex"); }
Source:
<code><START> void addOrderItem(List<SqlNode> orderByList, RexProgram program, RexFieldCollation field) { <END> SqlNode node = toSql(program, field.left); SqlNode nullDirectionNode = null; if (field.getNullDirection() != RelFieldCollation.NullDirection.UNSPECIFIED) { final boolean first = field.getNullDirection() == RelFieldCollation.NullDirection.FIRST; nullDirectionNode = dialect.emulateNullDirection( node, first, field.getDirection().isDescending()); } if (nullDirectionNode != null) { orderByList.add(nullDirectionNode); switch (field.getDirection()) { case DESCENDING: case STRICTLY_DESCENDING: node = SqlStdOperatorTable.DESC.createCall(POS, node); } orderByList.add(node); } else { orderByList.add(toSql(program, field)); } }</code><technical_language>private ? add some doc</technical_language>

Target:
private void addOrderItem(List<SqlNode> orderByList, RexProgram program, RexFieldCollation field) { SqlNode node = toSql(program, field.left); SqlNode nullDirectionNode = null; if (field.getNullDirection() != RelFieldCollation.NullDirection.UNSPECIFIED) { final boolean first = field.getNullDirection() == RelFieldCollation.NullDirection.FIRST; nullDirectionNode = dialect.emulateNullDirection( node, first, field.getDirection().isDescending()); } if (nullDirectionNode != null) { orderByList.add(nullDirectionNode); switch (field.getDirection()) { case DESCENDING: case STRICTLY_DESCENDING: node = SqlStdOperatorTable.DESC.createCall(POS, node); break; default: break; } orderByList.add(node); } else { orderByList.add(toSql(program, field)); } }
Source:
<code>public String modifyIdentifierTargetURL(DvObject dvObject) throws Exception { String identifier = getIdentifier(dvObject); HashMap<String, String> metadata = new HashMap<>(); metadata.put("_target", getTargetUrl(dvObject)); try { ezidService.setMetadata(identifier, <START> (metadata instanceof HashMap) ? (HashMap)metadata : new HashMap<>(metadata)); <END> return identifier; } catch (EZIDException e) { logger.log(Level.WARNING, "modifyMetadata failed"); logger.log(Level.WARNING, "String {0}", e.toString()); logger.log(Level.WARNING, "localized message {0}", e.getLocalizedMessage()); logger.log(Level.WARNING, "cause", e.getCause()); logger.log(Level.WARNING, "message {0}", e.getMessage()); throw e; } }</code><technical_language>line 132, metadata is a HashMap? that, bother this check</technical_language>

Target:
public String modifyIdentifierTargetURL(DvObject dvObject) throws Exception { String identifier = getIdentifier(dvObject); HashMap<String, String> metadata = new HashMap<>(); metadata.put("_target", getTargetUrl(dvObject)); try { ezidService.setMetadata(identifier,metadata); return identifier; } catch (EZIDException e) { logger.log(Level.WARNING, "modifyMetadata failed"); logger.log(Level.WARNING, "String {0}", e.toString()); logger.log(Level.WARNING, "localized message {0}", e.getLocalizedMessage()); logger.log(Level.WARNING, "cause", e.getCause()); logger.log(Level.WARNING, "message {0}", e.getMessage()); throw e; } }
Source:
<code>public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(getX1()); bits = 31 * bits + Double.doubleToLongBits(getY1()); bits = 31 * bits + Double.doubleToLongBits(getX2()); bits = 31 * bits + Double.doubleToLongBits(getY2()); final int b = (int) bits; <START> return b; <END> }</code><technical_language>Please replace change similar b ^ (b >> 31)</technical_language>

Target:
public int hashCode() { long bits = 1; bits = 31 * bits + Double.doubleToLongBits(getX1()); bits = 31 * bits + Double.doubleToLongBits(getY1()); bits = 31 * bits + Double.doubleToLongBits(getX2()); bits = 31 * bits + Double.doubleToLongBits(getY2()); final int b = (int) bits; return b ^ (b >> 31); }
Source:
<code>private void createReplLoadCompleteAckTask() { if ((work.isIncrementalLoad() && !work.incrementalLoadTasksBuilder().hasMoreWork() && !work.hasBootstrapLoadTasks()) || (!work.isIncrementalLoad() && !work.hasBootstrapLoadTasks())) { AckWork replLoadAckWork = new AckWork( new Path(work.dumpDirectory, LOAD_ACKNOWLEDGEMENT.toString())); Task<AckWork> loadAckWorkTask = TaskFactory.get(replLoadAckWork, conf); if (childTasks.isEmpty()) { <START> this.childTasks.add(loadAckWorkTask); <END> } else { DAGTraversal.traverse(this.childTasks, new AddDependencyToLeaves(Collections.singletonList(loadAckWorkTask))); } } }</code><technical_language>Remove this next line well</technical_language>

Target:
private void createReplLoadCompleteAckTask() { if ((work.isIncrementalLoad() && !work.incrementalLoadTasksBuilder().hasMoreWork() && !work.hasBootstrapLoadTasks()) || (!work.isIncrementalLoad() && !work.hasBootstrapLoadTasks())) { AckWork replLoadAckWork = new AckWork( new Path(work.dumpDirectory, LOAD_ACKNOWLEDGEMENT.toString())); Task<AckWork> loadAckWorkTask = TaskFactory.get(replLoadAckWork, conf); if (childTasks.isEmpty()) { childTasks.add(loadAckWorkTask); } else { DAGTraversal.traverse(childTasks, new AddDependencyToLeaves(Collections.singletonList(loadAckWorkTask))); } } }
Source:
<code><START> boolean ready() { <END> return true; }</code><technical_language>qualifier</technical_language>

Target:
public boolean ready() { return true; }
Source:
<code>public static void resetStatics() { carrierName = "test1"; subscribableStatus = 1; <START> isRunningOnMainThread = false; <END> supportsADM = false; hasFCMLibrary = false; isGMSInstalledAndEnabled = false; hasHMSAvailability = false; hasHMSPushKitLibrary = false; hasHMSAGConnectLibrary = false; isHMSCoreInstalledAndEnabled = false; }</code><technical_language>tests fail if this line</technical_language>

Target:
public static void resetStatics() { carrierName = "test1"; subscribableStatus = 1; supportsADM = false; hasFCMLibrary = false; isGMSInstalledAndEnabled = false; hasHMSAvailability = false; hasHMSPushKitLibrary = false; hasHMSAGConnectLibrary = false; isHMSCoreInstalledAndEnabled = false; }
Source:
<code>public void setKeyBinding(int key, int action) { checkWidget(); int modifierValue = key & SWT.MODIFIER_MASK; int keyInt = key & SWT.KEY_MASK; char keyChar = (char)keyInt; if (Character.isDefined(keyInt) && Compatibility.isLetter(keyChar)) { char ch = Character.toUpperCase(keyChar); int newKey = ch | modifierValue; if (action == SWT.NULL) { <START> keyActionMap.remove(new Integer(newKey)); } else { keyActionMap.put(new Integer(newKey), new Integer(action)); } ch = Character.toLowerCase(keyChar); newKey = ch | modifierValue; if (action == SWT.NULL) { keyActionMap.remove(new Integer(newKey)); } else { keyActionMap.put(new Integer(newKey), new Integer(action)); } } else { if (action == SWT.NULL) { keyActionMap.remove(new Integer(key)); } else { keyActionMap.put(new Integer(key), new Integer(action)); <END> } } }</code><technical_language>Revert</technical_language>

Target:
public void setKeyBinding(int key, int action) { checkWidget(); int modifierValue = key & SWT.MODIFIER_MASK; int keyInt = key & SWT.KEY_MASK; char keyChar = (char)keyInt; if (Character.isDefined(keyInt) && Compatibility.isLetter(keyChar)) { char ch = Character.toUpperCase(keyChar); int newKey = ch | modifierValue; if (action == SWT.NULL) { keyActionMap.remove(newKey); } else { keyActionMap.put(newKey, action); } ch = Character.toLowerCase(keyChar); newKey = ch | modifierValue; if (action == SWT.NULL) { keyActionMap.remove(newKey); } else { keyActionMap.put(newKey, action); } } else { if (action == SWT.NULL) { keyActionMap.remove(key); } else { keyActionMap.put(key, action); } } }
Source:
<code>public URL asUrl() { <START> return null; <END> }</code><technical_language>strange FileInputResources converted Path URL, Path is convertible URL -- do want address this a call asPath().toUri().toURL()</technical_language>

Target:
public URL asUrl() { try { return asPath().toUri().toURL(); } catch (MalformedURLException e) { return null; } }