auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void createNewTraceNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); GridData data = new GridData(GridData.FILL_HORIZONTAL); <START> data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; <END> String name = fTrace.getName(); Label newTaceLabel = new Label(folderGroup, SWT.NONE); newTaceLabel.setFont(font); newTaceLabel.setText(Messages.RenameTraceDialog_TraceNewName); fNewTraceNameText = new Text(folderGroup, SWT.BORDER); data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewTraceNameText.setLayoutData(data); fNewTraceNameText.setFont(font); fNewTraceNameText.setFocus(); fNewTraceNameText.setText(name); fNewTraceNameText.setSelection(0, name.length()); fNewTraceNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewTraceName(); } }); }</code><technical_language>Unused instance</technical_language>

Target:
private void createNewTraceNameGroup(Composite parent) { Font font = parent.getFont(); Composite folderGroup = new Composite(parent, SWT.NONE); GridLayout layout = new GridLayout(); layout.numColumns = 2; folderGroup.setLayout(layout); folderGroup.setLayoutData(new GridData(GridData.FILL_HORIZONTAL)); String name = fTrace.getName(); Label newTaceLabel = new Label(folderGroup, SWT.NONE); newTaceLabel.setFont(font); newTaceLabel.setText(Messages.RenameTraceDialog_TraceNewName); fNewTraceNameText = new Text(folderGroup, SWT.BORDER); GridData data = new GridData(GridData.FILL_HORIZONTAL); data.widthHint = IDialogConstants.ENTRY_FIELD_WIDTH; fNewTraceNameText.setLayoutData(data); fNewTraceNameText.setFont(font); fNewTraceNameText.setFocus(); fNewTraceNameText.setText(name); fNewTraceNameText.setSelection(0, name.length()); fNewTraceNameText.addListener(SWT.Modify, new Listener() { @Override public void handleEvent(Event event) { validateNewTraceName(); } }); }
Source:
<code><START> public List<TriggerEvent> getTriggers(int page, int pageSize) { <END> try (Connection conn = DBConnectionManager.getInstance().getConnection(sqlProperties.getProperty(DATA_SOURCE)); Statement stmt = conn.createStatement()) { ResultSet rs = stmt.executeQuery(buildGetTriggersQuery(page, pageSize)); List<TriggerEvent> triggers = new ArrayList<>(); while (rs.next()) { try (InputStream is = new ByteArrayInputStream(rs.getBytes(JOB_DATA)); ObjectInputStream ois = new ObjectInputStream(is)) { JobDataMap dataMap = (JobDataMap) ois.readObject(); triggers.add(new TriggerEvent( "Job: " + rs.getString(JOB_NAME), rs.getString(JOB_NAME), rs.getString(JOB_DESCRIPTION), new ArrayList<>(), dataMap.getString(SchedulerConstants.EVENT_TYPE_KEY_NAME) )); } } return triggers; } catch (Exception e) { throw new TriggerRetrievalException("Couldn't retrieve triggers for Scheduler channel", e); } }</code><technical_language>This belongs in service deals scheduler database</technical_language>

Target:
public List<TriggerEvent> getTriggers(int page, int pageSize) { try { return motechSchedulerDatabaseService.getTriggers(page, pageSize); } catch (SQLException|IOException|ClassNotFoundException e) { throw new TriggerRetrievalException("Couldn't retrieve triggers for Scheduler channel", e); } }
Source:
<code>public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(serializer)) { <START> return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); <END> } return Mono.fromCallable(() -> toObject(clazz, serializer)); }</code><technical_language>other toObject() overload checks if clazz is null. add check well</technical_language>

Target:
public <T> Mono<T> toObjectAsync(Class<T> clazz, ObjectSerializer serializer) { if (Objects.isNull(clazz)) { return monoError(LOGGER, new NullPointerException("'clazz' cannot be null.")); } else if (Objects.isNull(serializer)) { return monoError(LOGGER, new NullPointerException("'serializer' cannot be null.")); } return Mono.fromCallable(() -> toObject(clazz, serializer)); }
Source:
<code>ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { this.tableDefinitions = new HashMap<>(); try { for (File file : listFiles(config.getTableDescriptionDir())) { if (file.isFile() && file.getName().endsWith(".json")) { ElasticsearchTableDescription table = codec.fromJson(readAllBytes(file.toPath())); String schemaName = firstNonNull(table.getSchemaName(), config.getDefaultSchema()); tableDefinitions.put(new SchemaTableName(schemaName, table.getTableName()), table); } } for (String definedTable : config.getTableNames()) { SchemaTableName tableName = parseTableName(definedTable); if (!tableDefinitions.containsKey(tableName)) { <START> throw new PrestoException(ELASTICSEARCH_TABLE_DEFINITION_ERROR, "Missing table definition for: " + tableName); <END> } ElasticsearchTableDescription elasticsearchTable = tableDefinitions.get(tableName); tableDefinitions.put(tableName, elasticsearchTable); } } catch (IOException e) { throw new UncheckedIOException(e); } }</code><technical_language>I this method OK, do think? ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { requireNonNull(config, "config is null"); requireNonNull(codec, "codec is null"); this. tableDefinitions = createElasticsearchTableDescriptions(...); } public methods top</technical_language>

Target:
ElasticsearchTableDescriptionProvider(ElasticsearchConnectorConfig config, JsonCodec<ElasticsearchTableDescription> codec) { requireNonNull(config, "config is null"); requireNonNull(codec, "codec is null"); tableDefinitions = createTableDescriptions(config, codec); }
Source:
<code>public void buildVmVirtioScsi() { List<VmDevice> vmDevices = vmDeviceDao.getVmDeviceByVmIdTypeAndDevice( vm.getId(), VmDeviceGeneralType.CONTROLLER, VmDeviceType.VIRTIOSCSI.getName()); Map<DiskInterface, Integer> controllerIndexMap = ArchStrategyFactory.getStrategy(vm.getClusterArch()).run(new GetControllerIndices()).returnValue(); int virtioScsiIndex = controllerIndexMap.get(DiskInterface.VirtIO_SCSI); for (VmDevice vmDevice : vmDevices) { Map<String, Object> struct = new HashMap<>(); struct.put(VdsProperties.Type, VmDeviceGeneralType.CONTROLLER.getValue()); struct.put(VdsProperties.Device, VdsProperties.Scsi); struct.put(VdsProperties.Model, VdsProperties.VirtioScsi); struct.put(VdsProperties.Index, Integer.toString(virtioScsiIndex)); if (vm.getNumOfIoThreads() > 0) { struct.put(VdsProperties.ioTrheadId, Integer.toString(virtioScsiIndex)); <START> virtioScsiIndex++; <END> } vmInfoBuildUtils.addAddress(vmDevice, struct); virtioScsiIndex++; addDevice(struct, vmDevice, null); } }</code><technical_language>this virtioScsiIndex++; line 705 indexes 0, 2, 4... 0, 1, 2..</technical_language>

Target:
public void buildVmVirtioScsi() { List<VmDevice> vmDevices = vmDeviceDao.getVmDeviceByVmIdTypeAndDevice( vm.getId(), VmDeviceGeneralType.CONTROLLER, VmDeviceType.VIRTIOSCSI.getName()); Map<DiskInterface, Integer> controllerIndexMap = ArchStrategyFactory.getStrategy(vm.getClusterArch()).run(new GetControllerIndices()).returnValue(); int virtioScsiIndex = controllerIndexMap.get(DiskInterface.VirtIO_SCSI); for (VmDevice vmDevice : vmDevices) { Map<String, Object> struct = new HashMap<>(); struct.put(VdsProperties.Type, VmDeviceGeneralType.CONTROLLER.getValue()); struct.put(VdsProperties.Device, VdsProperties.Scsi); struct.put(VdsProperties.Model, VdsProperties.VirtioScsi); struct.put(VdsProperties.Index, Integer.toString(virtioScsiIndex)); if (vm.getNumOfIoThreads() > 0) { struct.put(VdsProperties.ioTrheadId, Integer.toString(virtioScsiIndex)); } vmInfoBuildUtils.addAddress(vmDevice, struct); virtioScsiIndex++; addDevice(struct, vmDevice, null); } }
Source:
<code>public void stop() { if (this.runningState != State.RUNNING && this.runningState != State.SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } if (this.runningState == State.RUNNING) { this.stopTime = System.nanoTime(); <START> split(""); <END> } this.runningState = State.STOPPED; }</code><technical_language>Please reuse StringUtils.EMPTY</technical_language>

Target:
public void stop() { if (this.runningState != State.RUNNING && this.runningState != State.SUSPENDED) { throw new IllegalStateException("Stopwatch is not running. "); } if (this.runningState == State.RUNNING) { this.stopTime = System.nanoTime(); split(StringUtils.EMPTY); } this.runningState = State.STOPPED; }
Source:
<code>public void stop() { LOG.info("Stopping Samza kafkaConsumer " + this); if (!stopped.compareAndSet(false, true)) { LOG.warn("attempting to stop stopped consumer."); return; } if (proxy != null) { LOG.info("Stopping proxy " + proxy); <START> proxy.stop(TimeUnit.MINUTES.toMillis(5)); <END> } try { synchronized (kafkaConsumer) { LOG.info("Closing kafka consumer " + kafkaConsumer); kafkaConsumer.close(); } } catch (Exception e) { LOG.warn("failed to stop SamzaRawKafkaConsumer + " + this, e); } }</code><technical_language>this wait for 5 mins stop proxy thread. set proxy thread stop timeout value</technical_language>

Target:
public void stop() { if (!stopped.compareAndSet(false, true)) { LOG.warn("{}: Attempting to stop stopped consumer.", this); return; } LOG.info("{}: Stopping Samza kafkaConsumer ", this); if (proxy != null) { LOG.info("{}: Stopping proxy {}", this, proxy); proxy.stop(TimeUnit.SECONDS.toMillis(60)); } try { synchronized (kafkaConsumer) { LOG.info("{}: Closing kafkaSystemConsumer {}", this, kafkaConsumer); kafkaConsumer.close(); } } catch (Exception e) { LOG.warn("{}: Failed to stop KafkaSystemConsumer.", this, e); } }
Source:
<code>public void createDocumentWithDebugLevel() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.DEBUG, APPENDER_NAME, consoleWriter); Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); <START> Assert.assertTrue(logger.isDebugEnabled()); <END> CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono<CosmosItemResponse> createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator<CosmosItemResponse> validator = new CosmosResponseValidator.Builder<CosmosItemResponse>() .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); } finally { safeClose(client); } }</code><technical_language>else please, ditto</technical_language>

Target:
public void createDocumentWithDebugLevel() throws Exception { final StringWriter consoleWriter = new StringWriter(); addAppenderAndLogger(NETWORK_LOGGING_CATEGORY, Level.DEBUG, APPENDER_NAME, consoleWriter); final Logger logger = LoggerFactory.getLogger(NETWORK_LOGGING_CATEGORY); assertThat(logger.isDebugEnabled()).isTrue(); CosmosClient client = clientBuilder().build(); try { CosmosItemProperties docDefinition = getDocumentDefinition(); Mono<CosmosItemResponse> createObservable = createdCollection.createItem(docDefinition, new CosmosItemRequestOptions()); CosmosResponseValidator<CosmosItemResponse> validator = new CosmosResponseValidator.Builder<CosmosItemResponse>() .withId(docDefinition.id()).build(); validateSuccess(createObservable, validator); assertThat(consoleWriter.toString()).isEmpty(); } finally { safeClose(client); } }
Source:
<code>private JnlpEndpointResolver createEndpointResolver(List<String> jenkinsUrls) { JnlpEndpointResolver resolver; if (instanceIdentity == null) { SSLSocketFactory sslSocketFactory = null; try { sslSocketFactory = getSSLSocketFactory(); } catch (Exception e) { <START> events.error(e); <END> } resolver = new JnlpAgentEndpointResolver(jenkinsUrls, credentials, proxyCredentials, tunnel, sslSocketFactory, disableHttpsCertValidation); } else { resolver = new JnlpAgentEndpointConfigurator(directUrl, instanceIdentity, protocols); } return resolver; }</code><technical_language>this return null error something? Otherwise, resolver = ... line partially initialized sound right me. default configurator in line 658</technical_language>

Target:
private JnlpEndpointResolver createEndpointResolver(List<String> jenkinsUrls) { JnlpEndpointResolver resolver; if (directConnection == null) { SSLSocketFactory sslSocketFactory = null; try { sslSocketFactory = getSSLSocketFactory(); } catch (Exception e) { events.error(e); } resolver = new JnlpAgentEndpointResolver(jenkinsUrls, credentials, proxyCredentials, tunnel, sslSocketFactory, disableHttpsCertValidation); } else { resolver = new JnlpAgentEndpointConfigurator(directConnection, instanceIdentity, protocols); } return resolver; }
Source:
<code>private synchronized void drainQueueForRequests() { <START> final PrefetchRecordsRetrieved recordsToDeliver = (PrefetchRecordsRetrieved) peekNextResult(); <END> if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }</code><technical_language>update peekNextResult() return PrefetchRecordsRetrieved type, need typecast here</technical_language>

Target:
synchronized void drainQueueForRequests() { final PrefetchRecordsRetrieved recordsToDeliver = peekNextResult(); if (publisherSession.hasDemandToPublish() && canDispatchRecord(recordsToDeliver)) { subscriber.onNext(recordsToDeliver.prepareForPublish()); recordsToDeliver.dispatched(); lastEventDeliveryTime = Instant.now(); } }
Source:
<code>private RelDataType decimalOf2(RelDataType type) { assert SqlTypeUtil.isNumeric(type) || SqlTypeUtil.isNull(type); SqlTypeName typeName = type.getSqlTypeName(); assert typeName != null; switch (typeName) { case DECIMAL: <START> return RelDataTypeFactoryImpl.isJavaType(type) <END> ? createSqlType(SqlTypeName.DECIMAL) : type; case TINYINT: return createSqlType(SqlTypeName.DECIMAL, 3, 0); case SMALLINT: return createSqlType(SqlTypeName.DECIMAL, 5, 0); case INTEGER: return createSqlType(SqlTypeName.DECIMAL, 10, 0); case BIGINT: return createSqlType(SqlTypeName.DECIMAL, 38, 0); case REAL: return createSqlType(SqlTypeName.DECIMAL, 14, 7); case FLOAT: return createSqlType(SqlTypeName.DECIMAL, 14, 7); case DOUBLE: return createSqlType(SqlTypeName.DECIMAL, 30, 15); default: return createSqlType(SqlTypeName.DECIMAL); } }</code><technical_language>createSqlType(SqlTypeName.DECIMAL) returns a decimal max precision 0 scale, a LONG type, for java decimal, return a max precision/scale decimal, method SqlTypeUtil#getMaxPrecisionScaleDecimal</technical_language>

Target:
private RelDataType decimalOf2(RelDataType type) { assert SqlTypeUtil.isNumeric(type) || SqlTypeUtil.isNull(type); SqlTypeName typeName = type.getSqlTypeName(); assert typeName != null; switch (typeName) { case DECIMAL: return RelDataTypeFactoryImpl.isJavaType(type) ? SqlTypeUtil.getMaxPrecisionScaleDecimal(this) : type; case TINYINT: return createSqlType(SqlTypeName.DECIMAL, 3, 0); case SMALLINT: return createSqlType(SqlTypeName.DECIMAL, 5, 0); case INTEGER: return createSqlType(SqlTypeName.DECIMAL, 10, 0); case BIGINT: return createSqlType(SqlTypeName.DECIMAL, 38, 0); case REAL: return createSqlType(SqlTypeName.DECIMAL, 14, 7); case FLOAT: return createSqlType(SqlTypeName.DECIMAL, 14, 7); case DOUBLE: return createSqlType(SqlTypeName.DECIMAL, 30, 15); default: return createSqlType(SqlTypeName.DECIMAL); } }
Source:
<code>public void addItem(ContextMenuItem item) { try { String id = item.getId(); if (id != null) { item.setHidden(isItemHidden(id)); item.setOrder(getItemOrder(id, item.getOrder())); } items.add(item.getPos(), item); <START> } catch (IndexOutOfBoundsException ex) { <END> items.add(item); } sortItemsByOrder(); }</code><technical_language>Bad code. Remove try - catch</technical_language>

Target:
public void addItem(ContextMenuItem item) { String id = item.getId(); if (id != null) { item.setHidden(isItemHidden(id)); item.setOrder(getItemOrder(id, item.getOrder())); } items.add(item); sortItemsByOrder(); }
Source:
<code>static void resolveAttribute(OperationContext context, AttributeDefinition attribute, String attributeSyntax, boolean defaults, boolean enhancedSyntax) throws OperationFailedException { final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false); final ModelNode subModel = resource.getModel(); if (enhancedSyntax) { context.getResult().set(EnhancedSyntaxSupport.resolveEnhancedSyntax(attributeSyntax, subModel)); } else if (subModel.hasDefined(attribute.getName())) { final ModelNode result = subModel.get(attribute.getName()); context.getResult().set(result); } else if (defaults && attribute.getDefaultValue() != null) { context.getResult().set(attribute.getDefaultValue()); if (attribute.getAlternatives() != null) { final ModelNode undefined = new ModelNode(); for(String alternative : attribute.getAlternatives()) { if(!undefined.equals(subModel.get(alternative))) { context.getResult().set(undefined); break; } } <START> } <END> } else { context.getResult(); } }</code><technical_language>This checking for alternatives a callout a separate method returns a boolean, callout added 'else if' check L283. if a default alternative, set result default, else drop 'else' case</technical_language>

Target:
static void resolveAttribute(OperationContext context, AttributeDefinition attribute, String attributeSyntax, boolean defaults, boolean enhancedSyntax) throws OperationFailedException { final Resource resource = context.readResource(PathAddress.EMPTY_ADDRESS, false); final ModelNode subModel = resource.getModel(); if (enhancedSyntax) { context.getResult().set(EnhancedSyntaxSupport.resolveEnhancedSyntax(attributeSyntax, subModel)); } else if (subModel.hasDefined(attribute.getName())) { final ModelNode result = subModel.get(attribute.getName()); context.getResult().set(result); } else if (defaults && attribute.getDefaultValue() != null) { if(!attribute.hasAlternative(subModel)) { context.getResult().set(attribute.getDefaultValue()); } else { final ModelNode undefined = new ModelNode(); for(final String alternative : attribute.getAlternatives()) { if(!undefined.equals(subModel.get(alternative))) { context.getResult().set(undefined); break; } } } } else { context.getResult(); } }
Source:
<code>protected boolean isValidateChainOfTrust() { try { <START> return propertyAccessor.getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, "ValiateChainOfTrust"); <END> } catch (PropertyAccessException ex) { LOG.error("Unable to read the Validate Chain of Trust logging property: {}", ex.getLocalizedMessage(), ex); } return false; }</code><technical_language>Validate spelled wrong. "ValidateChainOfTrust"</technical_language>

Target:
protected boolean isValidateChainOfTrust() { try { return propertyAccessor.getPropertyBoolean(NhincConstants.GATEWAY_PROPERTY_FILE, "ValidateChainOfTrust"); } catch (PropertyAccessException ex) { LOG.error("Unable to read the Validate Chain of Trust logging property " + ex.getLocalizedMessage(), ex); } return false; }
Source:
<code>public void should_set_entries_to_mdc_from_two_spans1() throws Exception { <START> Scope scope = this.slf4jCurrentTraceContext.newScope(this.span.context()); <END> assertMDCInfoEqualToSpanInfo(span.context()); Scope scopeInner = this.slf4jCurrentTraceContext.newScope(null); assertMDCInfoNullOrEmpty(); scopeInner.close(); assertMDCInfoEqualToSpanInfo(span.context()); scope.close(); assertMDCInfoNullOrEmpty(); }</code><technical_language>a small minor suggestion: Scope implements Closeable try-with-resources style</technical_language>

Target:
public void should_set_entries_to_mdc_from_two_spans1() throws Exception { try (Scope scope = this.slf4jCurrentTraceContext.newScope(this.span.context())) { assertMDCInfoEqualToSpanInfo(span.context()); try (Scope scopeInner = this.slf4jCurrentTraceContext.newScope(null)) { assertMDCInfoNullOrEmpty(); } assertMDCInfoEqualToSpanInfo(span.context()); } assertMDCInfoNullOrEmpty(); }
Source:
<code>public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, "addDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + "), GatewayAddr=" + mDefaultGatewayAddr); } InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); if (inetAddress == null) { <START> if (DBG) Log.d(TAG, " Unable to add default route."); <END> } else { NetworkUtils.addRoute(mInterfaceName, inetAddress, 0); mDefaultRouteSet = true; } } }</code><technical_language>vaguely worrying this function multiple failure modes indication of failure is a debug message if DBG is true. I imagine API is set in stone function changed return a value? Failing that, if addRoute fails, sense set mDefaultRouteSet true</technical_language>

Target:
public void addDefaultRoute() { if ((mInterfaceName != null) && (mDefaultGatewayAddr != 0) && mDefaultRouteSet == false) { if (DBG) { Log.d(TAG, "addDefaultRoute for " + mNetworkInfo.getTypeName() + " (" + mInterfaceName + "), GatewayAddr=" + mDefaultGatewayAddr); } InetAddress inetAddress = NetworkUtils.intToInetAddress(mDefaultGatewayAddr); if (inetAddress == null) { if (DBG) Log.d(TAG, " Unable to add default route. mDefaultGatewayAddr Error"); } else { if (NetworkUtils.addRoute(mInterfaceName, inetAddress, 0)) { mDefaultRouteSet = true; } else { if (DBG) Log.d(TAG, " Unable to add default route."); } } } }
Source:
<code>public void journalAttachDb() throws Exception { mClusterResource.start(); LocalAlluxioCluster mCluster = mClusterResource.get(); TableMaster tableMaster = mCluster.getLocalAlluxioMaster().getMasterProcess().getMaster(TableMaster.class); mException.expect(IOException.class); <START> tableMaster.getDatabase(DB_NAME); <END> tableMaster .attachDatabase(TestUdbFactory.TYPE, "connect", DB_NAME, DB_NAME, Collections.emptyMap()); assertEquals(DB_NAME, tableMaster.getDatabase(DB_NAME).getDbName()); List<String> oldTableNames = tableMaster.getAllTables(DB_NAME); Table tableOld = tableMaster.getTable(DB_NAME, oldTableNames.get(0)); mCluster.stopMasters(); TestDatabase.genTable(2, 2); mCluster.startMasters(); TableMaster tableMasterRestart = mCluster.getLocalAlluxioMaster().getMasterProcess().getMaster(TableMaster.class); List<String> newTableNames = tableMaster.getAllTables(DB_NAME); assertEquals(oldTableNames, newTableNames); Table tableNew = tableMasterRestart.getTable(DB_NAME, newTableNames.get(0)); assertEquals(tableOld.getName(), tableNew.getName()); }</code><technical_language>this stop rest of test run</technical_language>

Target:
public void journalAttachDb() throws Exception { mClusterResource.start(); LocalAlluxioCluster mCluster = mClusterResource.get(); TableMaster tableMaster = mCluster.getLocalAlluxioMaster().getMasterProcess().getMaster(TableMaster.class); try { tableMaster.getDatabase(DB_NAME); fail(); } catch (IOException e) { assertEquals("Database " + DB_NAME + " does not exist", e.getMessage()); } tableMaster .attachDatabase(TestUdbFactory.TYPE, "connect", DB_NAME, DB_NAME, Collections.emptyMap()); assertEquals(DB_NAME, tableMaster.getDatabase(DB_NAME).getDbName()); List<String> oldTableNames = tableMaster.getAllTables(DB_NAME); Table tableOld = tableMaster.getTable(DB_NAME, oldTableNames.get(0)); mCluster.stopMasters(); TestDatabase.genTable(2, 2); mCluster.startMasters(); TableMaster tableMasterRestart = mCluster.getLocalAlluxioMaster().getMasterProcess().getMaster(TableMaster.class); List<String> newTableNames = tableMaster.getAllTables(DB_NAME); assertEquals(oldTableNames, newTableNames); Table tableNew = tableMasterRestart.getTable(DB_NAME, newTableNames.get(0)); assertEquals(tableOld.getName(), tableNew.getName()); }
Source:
<code>public boolean saveQuery(final AvroDag avroDag) { final String queryId = avroDag.getQueryId(); try { final File storedFile = getQueryStoreFile(queryId); if (storedFile.exists()) { storedFile.delete(); LOG.log(Level.INFO, "Deleting a duplicate query file"); } <START> storedFile.getParentFile().mkdirs(); <END> final DataFileWriter<AvroDag> dataFileWriter = new DataFileWriter<>(avroDagDatumWriter); dataFileWriter.create(avroDag.getSchema(), storedFile); dataFileWriter.append(avroDag); dataFileWriter.close(); LOG.log(Level.INFO, "Query {0} has been stored to disk.", queryId); return true; } catch (final Exception e) { e.printStackTrace(); return false; } }</code><technical_language>do create directory here</technical_language>

Target:
public boolean saveQuery(final AvroDag avroDag) { final String queryId = avroDag.getQueryId(); try { final File storedFile = getQueryStoreFile(queryId); if (storedFile.exists()) { storedFile.delete(); LOG.log(Level.INFO, "Deleting a duplicate query file"); } final DataFileWriter<AvroDag> dataFileWriter = new DataFileWriter<>(avroDagDatumWriter); dataFileWriter.create(avroDag.getSchema(), storedFile); dataFileWriter.append(avroDag); dataFileWriter.close(); LOG.log(Level.INFO, "Query {0} has been stored to disk.", queryId); return true; } catch (final Exception e) { e.printStackTrace(); return false; } }
Source:
<code>public void testCreateTags() throws Exception { List<Tag> newTagsList = ImmutableList.of( new Tag.Builder() .name("Cloudsigma2 New tag") .meta(new HashMap<String, String>()) .build() , new Tag.Builder() .name("Cloudsigma2 tag with resource") .meta(new HashMap<String, String>()) .resources(ImmutableList.of( new TagResource.Builder() .uuid(createdDrive.getUuid()) .build() )) .build()); createdTags = api.createTags(newTagsList); <START> Assert.assertEquals(newTagsList.size(), createdTags.size()); <END> for(int i = 0; i < newTagsList.size(); i++){ checkTag(newTagsList.get(i), createdTags.get(i)); } }</code><technical_language>Static import? is "actual", is "expected" here? TestNG assertEquals(actual, expected), I suspect this wrong around..</technical_language>

Target:
public void testCreateTags() throws Exception { List<Tag> newTagsList = ImmutableList.of( new Tag.Builder().name("Cloudsigma2 New tag " + System.currentTimeMillis()) .meta(new HashMap<String, String>()).build(), new Tag.Builder().name("Cloudsigma2 tag with resource " + System.currentTimeMillis()) .meta(new HashMap<String, String>()) .resources(ImmutableList.of(new TagResource.Builder().uuid(createdDrive.getUuid()).build())).build()); createdTags = api.createTags(newTagsList); assertEquals(createdTags.size(), newTagsList.size()); for (int i = 0; i < newTagsList.size(); i++) { checkTag(newTagsList.get(i), createdTags.get(i)); } }
Source:
<code>public AdvancedCache<String, V> getCache(String name, MediaType requestedMediaType) { if (isCacheIgnored.test(name)) { <START> throw new ServiceUnavailableException("Cache with name '" + name + "' is temporarily unavailable."); <END> } if (requestedMediaType == null) { throw new NullPointerException("requestedMediaType cannot be null"); } AdvancedCache<String, V> registered = knownCaches.get(name + requestedMediaType.getTypeSubtype()); if (registered != null) return registered; checkCacheAvailable(name); AdvancedCache<String, V> cache = instance.<String, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); if (name.equals(PROTOBUF_METADATA_CACHE_NAME)) { cache = (AdvancedCache<String, V>) cache.withEncoding(UTF8CompatEncoder.class); } else { Configuration cacheConfiguration = cache.getCacheConfiguration(); if (cacheConfiguration.memory().storageType() == StorageType.OFF_HEAP) { cache = (AdvancedCache<String, V>) cache.withKeyEncoding(UTF8Encoder.class); } cache = (AdvancedCache<String, V>) cache.withMediaType(TEXT_PLAIN_TYPE, requestedMediaType.toString()); } knownCaches.putIfAbsent(name + requestedMediaType.getTypeSubtype(), cache); return cache; }</code><technical_language>i18n</technical_language>

Target:
public AdvancedCache<String, V> getCache(String name, MediaType requestedMediaType) { if (isCacheIgnored.test(name)) { throw logger.cacheUnavailable(name); } if (requestedMediaType == null) { throw logger.missingRequiredMediaType(name); } AdvancedCache<String, V> registered = knownCaches.get(name + requestedMediaType.getTypeSubtype()); if (registered != null) return registered; checkCacheAvailable(name); AdvancedCache<String, V> cache = instance.<String, V>getCache(name).getAdvancedCache(); tryRegisterMigrationManager(cache); if (name.equals(PROTOBUF_METADATA_CACHE_NAME)) { cache = (AdvancedCache<String, V>) cache.withEncoding(UTF8CompatEncoder.class); } else { Configuration cacheConfiguration = cache.getCacheConfiguration(); if (cacheConfiguration.memory().storageType() == StorageType.OFF_HEAP) { cache = (AdvancedCache<String, V>) cache.withKeyEncoding(UTF8Encoder.class); } cache = (AdvancedCache<String, V>) cache.withMediaType(TEXT_PLAIN_TYPE, requestedMediaType.toString()); } knownCaches.putIfAbsent(name + requestedMediaType.getTypeSubtype(), cache); return cache; }
Source:
<code>protected Bitmap doInBackground(String... params) { Bitmap result = null; if (params.length != 1) return result; String storagePath = params[0]; try { File picture = new File(storagePath); if (picture != null) { result = BitmapFactory.decodeStream(new FlushedInputStream (new BufferedInputStream(new FileInputStream(picture)))); } if (result == null) { mErrorMessageId = R.string.preview_image_error_unknown_format; Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath); } } catch (OutOfMemoryError e) { Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e); result = loadScaledImage(storagePath); if (result == null) { mErrorMessageId = R.string.preview_image_error_unknown_format; Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath); } } catch (NoSuchFieldError e) { mErrorMessageId = R.string.common_error_unknown; Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e); } catch (Throwable t) { mErrorMessageId = R.string.common_error_unknown; Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t); } <START> result = ThumbnailsCacheManager.rotateImage(result, storagePath); <END> return result; }</code><technical_language>This creates a dependency PreviewImageFragment - responsible for rendering handling input events for fragment showing images in preview gallery - ThumbnailsCacheManager - responsible for handling thumbnais, do in PreviewImageFragment. move static method rotataImage(...) .utils.BitmapUtils</technical_language>

Target:
protected Bitmap doInBackground(String... params) { Bitmap result = null; if (params.length != 1) return result; String storagePath = params[0]; try { File picture = new File(storagePath); if (picture != null) { result = BitmapFactory.decodeStream(new FlushedInputStream (new BufferedInputStream(new FileInputStream(picture)))); } if (result == null) { mErrorMessageId = R.string.preview_image_error_unknown_format; Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath); } } catch (OutOfMemoryError e) { Log_OC.e(TAG, "Out of memory occured for file " + storagePath, e); result = loadScaledImage(storagePath); if (result == null) { mErrorMessageId = R.string.preview_image_error_unknown_format; Log_OC.e(TAG, "File could not be loaded as a bitmap: " + storagePath); } } catch (NoSuchFieldError e) { mErrorMessageId = R.string.common_error_unknown; Log_OC.e(TAG, "Error from access to unexisting field despite protection; file " + storagePath, e); } catch (Throwable t) { mErrorMessageId = R.string.common_error_unknown; Log_OC.e(TAG, "Unexpected error loading " + getFile().getStoragePath(), t); } result = BitmapUtils.rotateImage(result, storagePath); return result; }
Source:
<code>private boolean fixValue(StringProperty property) { if (property == null) { return false; } boolean modified = false; String value = property.getValue(); <START> for (Map.Entry<String, String> translation : this.translations.entrySet()) { <END> if (StringUtils.equals(value, translation.getKey())) { R54690PhenoTips1195DataMigration.this.logger.debug( "Replacing with {}", translation.getKey(), translation.getValue()); property.setValue(translation.getValue()); modified = true; } } return modified; }</code><technical_language>This simpler as: if (translations.containsKey(value)) { R54690PhenoTips1195DataMigration.this.logger.debug("Replacing {}", value, translations.get(value)); property.setValue(translations.get(value)); modified = true; }</technical_language>

Target:
private boolean fixValue(StringProperty property) { if (property == null) { return false; } boolean modified = false; String value = property.getValue(); if (this.translations.containsKey(value)) { R54690PhenoTips1195DataMigration.this.logger.debug( "Replacing with {}", value, this.translations.get(value)); property.setValue(this.translations.get(value)); modified = true; } return modified; }
Source:
<code>public int getLengthInBytes() { <START> return ReadHeadInfo.ITEM_SIZE + mate0ReadSequence.getLength() + mate1ReadSequence.getLength(); <END> }</code><technical_language>careful of NPE's here..</technical_language>

Target:
public int getLengthInBytes() { int totalBytes = 0; totalBytes += 1; totalBytes += ReadHeadInfo.ITEM_SIZE; totalBytes += thisReadSequence != null ? thisReadSequence.getLength() : 0; totalBytes += mateReadSequence != null ? mateReadSequence.getLength() : 0; return totalBytes; }
Source:
<code>protected DirectiveDefinition(String name, Description description, List<InputValueDefinition> inputValueDefinitions, List<DirectiveLocation> directiveLocations, SourceLocation sourceLocation, List<Comment> comments, IgnoredChars ignoredChars, Map<String, String> additionalData) { super(sourceLocation, comments, ignoredChars, additionalData, description); this.name = name; <START> this.description = description; <END> this.inputValueDefinitions = inputValueDefinitions; this.directiveLocations = directiveLocations; }</code><technical_language>super class AbstractDescribedNode description, derived class description (otherwise is "overridden" in a obvious way)</technical_language>

Target:
protected DirectiveDefinition(String name, Description description, List<InputValueDefinition> inputValueDefinitions, List<DirectiveLocation> directiveLocations, SourceLocation sourceLocation, List<Comment> comments, IgnoredChars ignoredChars, Map<String, String> additionalData) { super(sourceLocation, comments, ignoredChars, additionalData, description); this.name = name; this.inputValueDefinitions = inputValueDefinitions; this.directiveLocations = directiveLocations; }
Source:
<code>public void stop() { _log.info("Stopping coordinator"); _shutdown = true; _eventQueue.put(CoordinatorEvent.NO_OP_EVENT); if (waitForEventThreadToJoin()) { return; } <START> if (stopEventThread()) { <END> return; } for (String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).getConnector().stop(); } catch (Exception ex) { _log.warn(String.format( "Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } for (DatastreamTask task : _assignedDatastreamTasks.values()) { ((EventProducer) task.getEventProducer()).shutdown(); } _adapter.disconnect(); _log.info("Coordinator stopped"); }</code><technical_language>nit: add empty line this</technical_language>

Target:
public void stop() { _log.info("Stopping coordinator"); _shutdown = true; _eventQueue.put(CoordinatorEvent.NO_OP_EVENT); if (waitForEventThreadToJoin()) { return; } if (stopEventThread()) { return; } for (String connectorType : _connectors.keySet()) { try { _connectors.get(connectorType).getConnector().stop(); } catch (Exception ex) { _log.warn(String.format( "Connector stop threw an exception for connectorType %s, " + "Swallowing it and continuing shutdown.", connectorType), ex); } } for (DatastreamTask task : _assignedDatastreamTasks.values()) { ((EventProducer) task.getEventProducer()).shutdown(false); } _adapter.disconnect(); _log.info("Coordinator stopped"); }
Source:
<code>public void close() { <START> checkState(initialized.get(), "Driver is not initialized"); <END> if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) { return; } exclusiveLock.interruptCurrentOwner(); tryWithLock(() -> TRUE); }</code><technical_language>Close is called in cleanup-after-exceptional-condition situations, do job. If is complain anything, this does</technical_language>

Target:
public void close() { if (!state.compareAndSet(State.ALIVE, State.NEED_DESTRUCTION)) { return; } exclusiveLock.interruptCurrentOwner(); tryWithLock(() -> TRUE); }
Source:
<code>public String interpolate( String path, ProfileActivationContext context ) throws InterpolationException { if ( path == null ) { return null; } RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); final File basedir = context.getProjectDirectory(); if ( basedir != null ) { interpolator.addValueSource( new AbstractValueSource( false ) { @Override public Object getValue( String expression ) { if ( "basedir".equals( expression ) ) { return basedir.getAbsolutePath(); } return null; } } ); } else if ( path.contains( "${basedir}" ) ) { return null; } interpolator.addValueSource( new MapBasedValueSource( context.getProjectProperties() ) ); interpolator.addValueSource( new MapBasedValueSource( context.getUserProperties() ) ); interpolator.addValueSource( new MapBasedValueSource( context.getSystemProperties() ) ); <START> path = interpolator.interpolate( path, "" ); <END> return pathTranslator.alignToBaseDirectory( path, basedir ); }</code><technical_language>try avoid reusing local variables</technical_language>

Target:
public String interpolate( String path, ProfileActivationContext context ) throws InterpolationException { if ( path == null ) { return null; } RegexBasedInterpolator interpolator = new RegexBasedInterpolator(); final File basedir = context.getProjectDirectory(); if ( basedir != null ) { interpolator.addValueSource( new AbstractValueSource( false ) { @Override public Object getValue( String expression ) { if ( "basedir".equals( expression ) ) { return basedir.getAbsolutePath(); } return null; } } ); } else if ( path.contains( "${basedir}" ) ) { return null; } interpolator.addValueSource( new MapBasedValueSource( context.getProjectProperties() ) ); interpolator.addValueSource( new MapBasedValueSource( context.getUserProperties() ) ); interpolator.addValueSource( new MapBasedValueSource( context.getSystemProperties() ) ); String absolutePath = interpolator.interpolate( path, "" ); return pathTranslator.alignToBaseDirectory( absolutePath, basedir ); }
Source:
<code>public NamespacedMBeanServer createMBeanServer(String namespace, MBeanServer parent) throws KeyAlreadyExistsException { requireNonNull(namespace, "namespace is null"); requireNonNull(parent, "parent is null"); String fullNamespace = namespace; if (baseNamespace != null && !baseNamespace.equals(GLOBAL)) { fullNamespace = baseNamespace + NamespacedMBeanServer.SEPARATOR + namespace; } if (registeredEntries.containsKey(namespace)) { <START> throw new KeyAlreadyExistsException(String.format("MBean namespace %s already registered in %s!", namespace, baseNamespace)); <END> } NamespacedMBeanServer namespaceManager = new NamespacedMBeanServer(fullNamespace, parent); registeredEntries.put(namespace, namespaceManager); return namespaceManager; }</code><technical_language>Static import format end error messages in</technical_language>

Target:
public NamespacedMBeanServer createMBeanServer(String namespace, MBeanServer parent) { requireNonNull(namespace, "namespace is null"); requireNonNull(parent, "parent is null"); String fullNamespace = namespace; if (!isGlobal(baseNamespace)) { fullNamespace = baseNamespace + NamespacedMBeanServer.SEPARATOR + namespace; } NamespacedMBeanServer namespaceManager = new NamespacedMBeanServer(fullNamespace, parent); if (registeredEntries.putIfAbsent(namespace, namespaceManager) != null) { throw new KeyAlreadyExistsException(format("MBean namespace %s already registered in %s", namespace, baseNamespace)); } return namespaceManager; }
Source:
<code>private static Timer timer( MeterRegistry meterRegistry, String interactionModel, SignalType signalType, Tag... tags) { return meterRegistry.timer( <START> String.format("rsocket.%s", interactionModel), <END> Tags.of(tags).and("signal.type", signalType.name())); }</code><technical_language>nit: String.format overkill compare "rsocket." + interactionModel, interactionModel is a String</technical_language>

Target:
private static Timer timer( MeterRegistry meterRegistry, String interactionModel, SignalType signalType, Tag... tags) { return meterRegistry.timer( "rsocket." + interactionModel, Tags.of(tags).and("signal.type", signalType.name())); }
Source:
<code><START> private SampleTissue buildTissue() { <END> SampleTissue tissue = new SampleTissueImpl(); tissue.setTimesReceived(timesReceived); tissue.setTubeNumber(tubeNumber); tissue.setPassageNumber(passageNumber); tissue.setTissueType(tissueType); tissue.setTissueOrigin(tissueOrigin); tissue.setExternalInstituteIdentifier(externalInstituteIdentifier); tissue.setLab(lab); return tissue; }</code><technical_language>tissueMaterial region set in</technical_language>

Target:
private SampleTissue buildTissue() { SampleTissue tissue = new SampleTissueImpl(); tissue.setTimesReceived(timesReceived); tissue.setTubeNumber(tubeNumber); tissue.setPassageNumber(passageNumber); tissue.setTissueType(tissueType); tissue.setTissueOrigin(tissueOrigin); tissue.setExternalInstituteIdentifier(externalInstituteIdentifier); tissue.setLab(lab); tissue.setTissueMaterial(tissueMaterial); tissue.setRegion(region); return tissue; }
Source:
<code><START> private void setCowVirtualSizeAndQcowCompat(DiskImage <END> diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); if (qcow2Signature == QCOW2_SIGNATURE && QCOW2_VERSIONS.contains(qcow2Version)) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); if (qcow2Version == 2) { diskImage.setQcowCompat(QcowCompat.QCOW2_V2); } else { diskImage.setQcowCompat(QcowCompat.QCOW2_V3); } } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }</code><technical_language>arbitrary decision group properties together. properties done other properties in separate methods? unify this all</technical_language>

Target:
private void setCowVirtualSizeAndQcowCompat(DiskImage diskImage, Image glanceImage) { byte[] imgContent = new byte[72]; ImageDownload downloadImage = getClient().images().download(glanceImage.getId()).execute(); try (InputStream inputStream = downloadImage.getInputStream()) { int bytesRead = inputStream.read(imgContent, 0, imgContent.length); if (bytesRead != imgContent.length) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to read image header: " + bytesRead); } } catch (IOException e) { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNABLE_TO_DOWNLOAD_IMAGE, "Unable to download image"); } ByteBuffer b = ByteBuffer.wrap(imgContent); int qcow2Signature = b.getInt(); int qcow2Version = b.getInt(); if (qcow2Signature == QCOW2_SIGNATURE && QCOW2_VERSIONS.contains(qcow2Version)) { b.position(QCOW2_SIZE_OFFSET); diskImage.setSize(b.getLong()); diskImage.setQcowCompat(QcowCompat.forQcowHeaderVersion(qcow2Version)); } else { throw new OpenStackImageException( OpenStackImageException.ErrorType.UNRECOGNIZED_IMAGE_FORMAT, "Unable to recognize QCOW2 format"); } }
Source:
<code>public LibraryContextSwitchEvent( EventType eventType ) { <START> this.eventType = eventType; <END> }</code><technical_language>Is worth null checks</technical_language>

Target:
public LibraryContextSwitchEvent( EventType eventType ) { checkNotNull( "eventType", eventType ); this.eventType = eventType; }
Source:
<code>private Cache<KeyValuePair<String, Class>, Object> getCache() { <START> if (cache == null) { <END> synchronized (this) { if (cache == null) { if (cacheManager.getCacheConfiguration(QUERY_CACHE_NAME) == null) { cacheManager.defineConfiguration(QUERY_CACHE_NAME, getDefaultQueryCacheConfig().build()); } cache = cacheManager.getCache(QUERY_CACHE_NAME); } } } return cache; }</code><technical_language>consider assigning cache field a local variable return instead? Cache result = cache; // Do double checked locking return result; [1], perf gain 25%, if this holds for modern JVMs [1] Effective Java 2nd Edition Page 284</technical_language>

Target:
private Cache<KeyValuePair<String, Class>, Object> getCache() { Cache<KeyValuePair<String, Class>, Object> cache = lazyCache; if (cache == null) { synchronized (this) { if (lazyCache == null) { if (cacheManager.getCacheConfiguration(QUERY_CACHE_NAME) == null) { cacheManager.defineConfiguration(QUERY_CACHE_NAME, getDefaultQueryCacheConfig().build()); } cache = lazyCache = cacheManager.getCache(QUERY_CACHE_NAME); } } } return cache; }
Source:
<code>public void start() { int INTERVAL = 1; <START> expirationExecutor.scheduleAtFixedRate(() -> doDataExpiration(dataRegion), INTERVAL, INTERVAL, <END> SECONDS); }</code><technical_language>I this potentially scheduleWithFixedDelay a guaranteed pause runs. concerned a large data set result in doDataExpiration longer 1 putting pressure system constantly running back-to-back</technical_language>

Target:
public void start() { int INTERVAL = 1; expirationExecutor.scheduleWithFixedDelay(() -> doDataExpiration(dataRegion), INTERVAL, INTERVAL, SECONDS); }