auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void addHadoopProperties(Props props) { props.put(injectPrefix + "azkaban.flow.flowid", props.get("azkaban.flow.flowid")); props.put(injectPrefix + "azkaban.flow.execid", props.get("azkaban.flow.execid")); props.put(injectPrefix + "azkaban.job.id", props.get("azkaban.job.id")); props.put(injectPrefix + "azkaban.flow.projectname", props.get("azkaban.flow.projectname")); props.put(injectPrefix + "azkaban.flow.projectversion", props.get("azkaban.flow.projectversion")); props.put(injectPrefix + "azkaban.flow.projectlastchangeddate", props.get("azkaban.flow.projectlastchangeddate")); <START> props.put(injectPrefix + "azkaban.flow.projectlasychangedby", props.get("azkaban.flow.projectlasychangedby")); <END> }</code><technical_language>Please constants defined in CommonJobProperties.java: <LINK_0></technical_language>

Target:
private static void addHadoopProperties(Props props) { String[] propsToInject = new String[]{ CommonJobProperties.EXEC_ID, CommonJobProperties.JOB_ID, CommonJobProperties.PROJECT_NAME, CommonJobProperties.PROJECT_VERSION, CommonJobProperties.EXECUTION_LINK, CommonJobProperties.JOB_LINK, CommonJobProperties.WORKFLOW_LINK, CommonJobProperties.JOBEXEC_LINK, CommonJobProperties.ATTEMPT_LINK, CommonJobProperties.OUT_NODES, CommonJobProperties.IN_NODES, CommonJobProperties.PROJECT_LAST_CHANGED_DATE, CommonJobProperties.PROJECT_LAST_CHANGED_BY }; for(String propertyName : propsToInject) { addHadoopProperty(props, propertyName); } }
Source:
<code>protected int processArgument(String[] args, int current) throws Exception { if (args[current].equals("-c")) <START> bracketedOutput = false; <END> else { if (new File(args[current]).exists()) { logger.info("Loading properties from " + args[current]); this.resourceManager = new ResourceManager(args[current]); logger.info("Completed loading properties."); } else throw new RuntimeException("The configuration file \"" + args[current] + "\" did not exist."); } return current++; }</code><technical_language>a command line app -- print STDOUT (or STDERR if a warning etc)</technical_language>

Target:
protected int processArgument(String[] args, int current) throws Exception { if (args[current].equals("-c")) bracketedOutput = false; else { if (new File(args[current]).exists()) { System.out.println("Loading properties from " + args[current]); this.resourceManager = new ResourceManager(args[current]); System.out.println("Completed loading properties."); } else throw new RuntimeException("The configuration file \"" + args[current] + "\" did not exist."); } return current++; }
Source:
<code>private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("%04x", packetLength) + " is causing buffer overrun."); } <START> if (blockLength > Integer.MAX_VALUE) { <END> throw new BadPcapFileException(String.format("%04x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength - 12); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("%04x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - 12); return pcapPacketData; }</code><technical_language>This is impossible, blockLength is int</technical_language>

Target:
private ByteBuffer parseCBPayLoad(ByteBuffer pcapPacketHeader, int blockLength) throws IOException, BadPcapFileException { ByteBuffer pcapPacketData; pcapPacketHeader.getInt(); long packetLength = ConversionHelper.unsignedIntToLong(blockLength); SeekableByteChannel fileChannel = getFileChannel(); if (fileChannel.size() - fileChannel.position() < packetLength) { throw new BadPcapFileException(String.format("0x%08x", packetLength) + " is causing buffer overrun."); } if (blockLength > Integer.MAX_VALUE) { throw new BadPcapFileException(String.format("0x%08x", blockLength) + " packet length is bigger than 2^31-1 bytes are not supported."); } pcapPacketData = ByteBuffer.allocate((int) packetLength - 12); pcapPacketData.clear(); ByteOrder byteOrder = getByteOrder(); pcapPacketHeader.order(byteOrder); int payLoad = fileChannel.read(pcapPacketData); if (payLoad == 0) { throw new BadPcapFileException(String.format("0x%08x", payLoad) + " is a bad payload."); } pcapPacketData.flip(); fileChannel.position(fileChannel.position() + blockLength - 12); return pcapPacketData; }
Source:
<code>public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); @SuppressWarnings("unchecked") Class<T> rootBeanClass = (Class<T>) object.getClass(); BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); if ( !rootBeanMetaData.hasConstraints() ) { return Collections.emptySet(); } BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object ); <START> if ( !validationContext.getRootBeanMetaData().hasConstraints() ) { <END> return Collections.emptySet(); } ValidationOrder validationOrder = determineGroupValidationOrder( groups ); BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); return validateInContext( validationContext, valueContext, validationOrder ); }</code><technical_language>this is redundant checked for constraints line 158</technical_language>

Target:
public final <T> Set<ConstraintViolation<T>> validate(T object, Class<?>... groups) { Contracts.assertNotNull( object, MESSAGES.validatedObjectMustNotBeNull() ); sanityCheckGroups( groups ); @SuppressWarnings("unchecked") Class<T> rootBeanClass = (Class<T>) object.getClass(); BeanMetaData<T> rootBeanMetaData = beanMetaDataManager.getBeanMetaData( rootBeanClass ); if ( !rootBeanMetaData.hasConstraints() ) { return Collections.emptySet(); } BaseBeanValidationContext<T> validationContext = getValidationContextBuilder().forValidate( rootBeanClass, rootBeanMetaData, object ); ValidationOrder validationOrder = determineGroupValidationOrder( groups ); BeanValueContext<?, Object> valueContext = ValueContexts.getLocalExecutionContextForBean( validatorScopedContext.getParameterNameProvider(), object, validationContext.getRootBeanMetaData(), PathImpl.createRootPath() ); return validateInContext( validationContext, valueContext, validationOrder ); }
Source:
<code>public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); <START> if (pageNumber < (totalCount / pageSize)) { <END> return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }</code><technical_language>pageNumber start 1 0? If starts one, this conditional wrong: pageNumber=1, totalCount=7,pageSize=5 return false, is a next page</technical_language>

Target:
public Optional<Object> nextMarker() { if (totalCount < pageSize) return Optional.absent(); if ((float) pageNumber < ((float) totalCount / (float) pageSize)) { return Optional.of(toPaginationOptions(pageNumber + 1)); } return Optional.absent(); }
Source:
<code>public static void writeJobModel(JobModel jobModel, String jobModelVersion, MetadataStore metadataStore) { try { List<byte[]> jobModelSegments = chunkJobModel(jobModel); <START> for (int jobModelSegmentIndex = 0; jobModelSegmentIndex < jobModelSegments.size(); jobModelSegmentIndex += 1) { <END> String jobModelSegmentKey = getJobModelSegmentKey(jobModelVersion, jobModelSegmentIndex); metadataStore.put(jobModelSegmentKey, jobModelSegments.get(jobModelSegmentIndex)); } } catch (Exception e) { throw new SamzaException(String.format("Exception occurred when storing JobModel: %s with version: %s.", jobModel, jobModelVersion), e); } }</code><technical_language>++</technical_language>

Target:
public static void writeJobModel(JobModel jobModel, String jobModelVersion, MetadataStore metadataStore) { try { String jobModelSerializedAsString = MAPPER.writeValueAsString(jobModel); byte[] jobModelSerializedAsBytes = jobModelSerializedAsString.getBytes(UTF_8); String metadataStoreKey = getJobModelKey(jobModelVersion); metadataStore.put(metadataStoreKey, jobModelSerializedAsBytes); } catch (Exception e) { throw new SamzaException(String.format("Exception occurred when storing JobModel: %s with version: %s.", jobModel, jobModelVersion), e); } }
Source:
<code><START> private ConnectorTableMetadata getTableMetadata(SchemaTableName tableName) <END> { ElasticsearchTableDescription table = client.getTable(tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return null; } return new ConnectorTableMetadata(tableName, client.getColumnMetadata(table)); }</code><technical_language>Update this method return Optional<ConnectorTableMetadata></technical_language>

Target:
private Optional<ConnectorTableMetadata> getTableMetadata(SchemaTableName tableName) { ElasticsearchTableDescription table = client.getTable(tableName.getSchemaName(), tableName.getTableName()); if (table == null) { return Optional.empty(); } return Optional.of(new ConnectorTableMetadata(tableName, client.getColumnMetadata(table))); }
Source:
<code>private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); <START> if (container == null) <END> return; List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); }</code><technical_language>brackets for single statements (I inconsitent this goal)</technical_language>

Target:
private void closeSideParts(MPart part, boolean left) { MElementContainer<MUIElement> container = getParent(part); if (container == null) { return; } List<MPart> others = getCloseableSideParts(part, left); closeSiblingParts(part, others, true); }
Source:
<code>private IStatus createResultStatus(Object result) { if (result == null) { return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, ""); } <START> StringBuilder message = new StringBuilder(); final String type = result.getClass().getSimpleName(); message.append(MessageFormat.format(Messages.SiriusEvaluationTask_status_resultType, type)); String size = null; if (result instanceof String) { size = String.valueOf(((String) result).length()); } else if (result instanceof Collection<?>) { size = String.valueOf(((Collection<?>) result).size()); } if (size != null) { message.append(" "); message.append(MessageFormat.format(Messages.SiriusEvaluationTask_status_resultSize, size)); } return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, message.toString()); <END> }</code><technical_language>This assumes/imposes sentence structure order in languages. Instead 2 templates for 2 cases, translated appropriately</technical_language>

Target:
private IStatus createResultStatus(Object result) { if (result == null) { return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, ""); } final String type = result.getClass().getSimpleName(); String size = null; if (result instanceof String) { size = String.valueOf(((String) result).length()); } else if (result instanceof Collection<?>) { size = String.valueOf(((Collection<?>) result).size()); } String message; if (size == null) { message = MessageFormat.format(Messages.SiriusEvaluationTask_status_resultMessage, type); } else { message = MessageFormat.format(Messages.SiriusEvaluationTask_status_sizedResultMessage, type, size); } return new Status(IStatus.OK, InterpreterViewPlugin.PLUGIN_ID, message); }
Source:
<code>public void testBlockUseHostCpuWithPPCArch() { when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); doNothing().when(cmd).initTemplateDisks(); setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); initPpcCluster(); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(anyInt())).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(OsType.Other.ordinal()); cmd.init(); <START> Map<String, String> migrationMap = new HashMap<String, String>() { { put("undefined", "true"); put("x86", "true"); put("ppc", "true"); } }; <END> mcr.mockConfigValue(ConfigValues.IsMigrationSupported, cmd.getEffectiveCompatibilityVersion(), migrationMap); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }</code><technical_language>This creates anonymous class extends HashMap, is considered a bad practice. for a simpler approach: Map<String, String> migrationMap = new HashMap<>(); migrationMap.put("undefined", "true"); migrationMap.put("x86", "true"); migrationMap.put("ppc", "true");</technical_language>

Target:
public void testBlockUseHostCpuWithPPCArch() { when(cpuFlagsManagerHandler.getCpuId(anyString(), any(Version.class))).thenReturn(CPU_ID); when(osRepository.isCpuSupported(anyInt(), any(Version.class), anyString())).thenReturn(true); doNothing().when(cmd).initTemplateDisks(); setupCanAddPpcTest(); cmd.setEffectiveCompatibilityVersion(Version.v4_0); doReturn(Collections.emptyList()).when(cmd).getImagesToCheckDestinationStorageDomains(); initPpcCluster(); doReturn(true).when(cmd).validateAddVmCommand(); doReturn(true).when(cmd).isVmNameValidLength(any(VM.class)); when(osRepository.getArchitectureFromOS(anyInt())).thenReturn(ArchitectureType.ppc64); cmd.getParameters().getVm().setClusterArch(ArchitectureType.ppc64); cmd.getParameters().getVm().setUseHostCpuFlags(true); cmd.getParameters().getVm().setMigrationSupport(MigrationSupport.PINNED_TO_HOST); cmd.getParameters().getVm().setClusterId(cluster.getId()); cmd.getParameters().getVm().setVmOs(OsType.Other.ordinal()); cmd.init(); Map<String, String> migrationMap = new HashMap<>(); migrationMap.put("undefined", "true"); migrationMap.put("x86", "true"); migrationMap.put("ppc", "true"); mcr.mockConfigValue(ConfigValues.IsMigrationSupported, cmd.getEffectiveCompatibilityVersion(), migrationMap); ValidateTestUtils.runAndAssertValidateFailure(cmd, EngineMessage.USE_HOST_CPU_REQUESTED_ON_UNSUPPORTED_ARCH); }
Source:
<code>public void removed(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { E existingElement = get(element.getUID()); onRemoveElement(existingElement); elements.remove(existingElement); <START> notifyListenersAboutRemovedElement(element); <END> } catch (Exception ex) { logger.warn("Could not remove element: {}", ex.getMessage(), ex); } } }</code><technical_language>a quick browse-through: notifyListenersAboutRemovedElement(...) called existingElement</technical_language>

Target:
public void removed(Provider<E> provider, E element) { Collection<E> elements = elementMap.get(provider); if (elements != null) { try { E existingElement = get(element.getUID()); onRemoveElement(existingElement); elements.remove(existingElement); notifyListenersAboutRemovedElement(existingElement); } catch (Exception ex) { logger.warn("Could not remove element: {}", ex.getMessage(), ex); } } }
Source:
<code>public void updateConditionFromEntity(boolean checkForDestruction) { final String METHOD_NAME = "updateConditionFromEntity()"; if(null != unit) { Mounted mounted = unit.getEntity().getEquipment(equipmentNum); if (!(mounted.getType() instanceof AmmoType)) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has invalid ammo bin at equipment number " + equipmentNum); } <START> if(null != mounted && mounted.getType() instanceof AmmoType) { <END> capacity = mounted.getAmmoCapacity(); type = mounted.getType(); if(mounted.isMissing() || mounted.isDestroyed()) { mounted.setShotsLeft(0); return; } shotsNeeded = getFullShots() - mounted.getBaseShotsLeft(); } } }</code><technical_language>need a null check mounted calling mounted.getType(). suggest moving logic if statement line 280 if statement line 276, making 280 "else"</technical_language>

Target:
public void updateConditionFromEntity(boolean checkForDestruction) { final String METHOD_NAME = "updateConditionFromEntity()"; if(null != unit) { Mounted mounted = unit.getEntity().getEquipment(equipmentNum); if (mounted == null) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has a null Mounted at equipment number " + equipmentNum); return; } if (!(mounted.getType() instanceof AmmoType)) { MekHQ.getLogger().log(LargeCraftAmmoBin.class, METHOD_NAME, LogLevel.WARNING, unit.getName() + " has an " + mounted.getName() + " that thinks it's an ammo bin at equipment number " + equipmentNum); } else { capacity = mounted.getAmmoCapacity(); type = mounted.getType(); if(mounted.isMissing() || mounted.isDestroyed()) { mounted.setShotsLeft(0); return; } shotsNeeded = getFullShots() - mounted.getBaseShotsLeft(); } } }
Source:
<code>public void setRequiredAttributes(List<String> requiredAttributes) { <START> this.requiredAttributes = requiredAttributes; <END> }</code><technical_language>list of required attributes validated list of editable attributes</technical_language>

Target:
public void setRequiredAttributes(List<String> requiredAttributes) { this.requiredAttributes = new LinkedHashSet<>(); for (String entry : requiredAttributes) { if (StringUtils.isNotBlank(entry)) { this.requiredAttributes.add(entry); } } }
Source:
<code>public byte[] getContent() { <START> return request.getEntity() != null ? request.getEntity().toString().getBytes(Charset.forName("UTF-8")) : null; <END> }</code><technical_language>Use: return Optional.fromNullable(request.getEntity()).transform(Functions.toStringFunction()).or("").getBytes(Charset.forName("UTF-8"));</technical_language>

Target:
public byte[] getContent() { return Optional.fromNullable(request.getEntity()).transform(toStringFunction()).or("").getBytes(Charset.forName("UTF-8")); }
Source:
<code>public void execute(IProgressMonitor monitor) throws CoreException { try { op.execute(monitor); } catch (CoreException e) { LockFailedException lockException = unwind(e); if (lockException != null) <START> UIUtils.handleLockDelete(lockException); <END> } }</code><technical_language>Exceptions other LockException need re-thrown. Jobs executing operation treated executed successfully. Other question: a Job executing operation treated successful if happens: 1. Operation fails lock failure 2. User removes lock confirming pop</technical_language>

Target:
public void execute(IProgressMonitor monitor) throws CoreException { try { op.execute(monitor); } catch (CoreException e) { LockFailedException lockException = unwind(e); if (lockException != null) UIUtils.promptToDeleteLock(lockException); else throw e; } }
Source:
<code>public void addExecutionPlan(String executionPlan) throws RemoteException { try { eventProcessorAdminServiceStub.deployExecutionPlan(executionPlan); } catch (RemoteException e) { log.error("RemoteException", e); <START> throw new RemoteException(e.getMessage(), e); <END> } }</code><technical_language>@thiliA fix this exception well</technical_language>

Target:
public void addExecutionPlan(String executionPlan) throws RemoteException { try { eventProcessorAdminServiceStub.deployExecutionPlan(executionPlan); } catch (RemoteException e) { log.error("RemoteException", e); throw e; } }
Source:
<code>public EventBookingDTO createBookingOrAddToWaitingList(final IsaacEventPageDTO event, final RegisteredUserDTO user, final Map<String, String> additionalEventInformation) throws SegueDatabaseException, DuplicateBookingException { if (this.isUserBooked(event.getId(), user.getId())) { throw new DuplicateBookingException(String.format("Unable to book onto event (%s) as user (%s) is already" + " booked on to it.", event.getId(), user.getEmail())); } EventBookingDTO booking; try { <START> this.bookingPersistenceManager.acquireDistributedLock(event.getId()); <END> try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.CONFIRMED); } catch (EventIsFullException e) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } } } finally { this.bookingPersistenceManager.releaseDistributedLock(event.getId()); } return booking; }</code><technical_language>code grab lock for this event ID then, acquiring it, in createBooking(...) method result in deadlock</technical_language>

Target:
public EventBookingDTO createBookingOrAddToWaitingList(final IsaacEventPageDTO event, final RegisteredUserDTO user, final Map<String, String> additionalEventInformation) throws SegueDatabaseException, DuplicateBookingException { if (this.isUserBooked(event.getId(), user.getId())) { throw new DuplicateBookingException(String.format("Unable to book onto event (%s) as user (%s) is already" + " booked on to it.", event.getId(), user.getEmail())); } EventBookingDTO booking; if (EventStatus.WAITING_LIST_ONLY.equals(event.getEventStatus())) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } return booking; } try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.CONFIRMED); } catch (EventIsFullException e) { try { booking = this.createBooking(event, user, additionalEventInformation, BookingStatus.WAITING_LIST); } catch (EventIsFullException e1) { throw new RuntimeException("Creating a waiting list booking should never throw an event is full exception " + "- something went terribly wrong for this to have happened", e1); } } return booking; }
Source:
<code>public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); <START> if(BuildConfig.elementSDK) { <END> ElementSDKManager.initElementSDK(this); } mInstance = this; if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } else { FlowLog.setMinimumLoggingLevel(FlowLog.Level.V); } PreferencesState.getInstance().init(getApplicationContext()); FlowConfig flowConfig = new FlowConfig .Builder(this) .addDatabaseHolder(EyeSeeTeaGeneratedDatabaseHolder.class) .build(); FlowManager.init(flowConfig); initBugShaker(); }</code><technical_language>This init happen (see dependency created import ElementSDKManager). Instead of that, I rely ElementController for purpose. a plugin initialization Controllers need initialized simply subscribe initialized here, if much, a dependency generic controller element SDK</technical_language>

Target:
public void onCreate() { super.onCreate(); Log.d(TAG, "onCreate"); if(BuildConfig.elementSDK) { IExternalVoucherRegistry elementController = new ElementController(getApplicationContext()); InitExternalVoucherRegisterUseCase initExternalVoucherRegisterUseCase = new InitExternalVoucherRegisterUseCase(elementController); initExternalVoucherRegisterUseCase.execute(); } mInstance = this; if (!BuildConfig.DEBUG) { Fabric.with(this, new Crashlytics()); } else { FlowLog.setMinimumLoggingLevel(FlowLog.Level.V); } PreferencesState.getInstance().init(getApplicationContext()); FlowConfig flowConfig = new FlowConfig .Builder(this) .addDatabaseHolder(EyeSeeTeaGeneratedDatabaseHolder.class) .build(); FlowManager.init(flowConfig); initBugShaker(); }
Source:
<code>@Override public GmmPartitionData build(LearningEnvironment env, Iterator<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, EmptyContext ctx) { <START> List<LabeledVector<Double>> xs = new ArrayList<>((int)upstreamDataSize); <END> double[][] pcxi = new double[(int)upstreamDataSize][]; int counter = 0; while (upstreamData.hasNext()) { UpstreamEntry<K, V> entry = upstreamData.next(); LabeledVector<Double> x = extractor.extract(entry.getKey(), entry.getValue()); xs.add(x); pcxi[counter] = new double[countOfComponents]; counter++; } return new GmmPartitionData(xs, pcxi); }</code><technical_language>Math.toIntExact()</technical_language>

Target:
@Override public GmmPartitionData build(LearningEnvironment env, Iterator<UpstreamEntry<K, V>> upstreamData, long upstreamDataSize, EmptyContext ctx) { int rowsCount = Math.toIntExact(upstreamDataSize); List<LabeledVector<Double>> xs = new ArrayList<>(rowsCount); double[][] pcxi = new double[rowsCount][countOfComponents]; while (upstreamData.hasNext()) { UpstreamEntry<K, V> entry = upstreamData.next(); LabeledVector<Double> x = extractor.extract(entry.getKey(), entry.getValue()); xs.add(x); } return new GmmPartitionData(xs, pcxi); }
Source:
<code>private Socket applySNI(final Socket socket, String hostname) { if (skipSNIApplication.get()) { <START> LOG.log(Level.FINE, "Skipping application of SNI because IBM JDK is missing setHost() method."); <END> return socket; } if (socket instanceof SSLSocket) { try { Method setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { @Override public Method run() throws NoSuchMethodException { return socket.getClass().getMethod("setHost", String.class); } }); setHostMethod.invoke(socket, hostname); LOG.log(Level.FINEST, "Applied SNI to socket for host {0}", hostname); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchMethodException && Environment.IS_IBM_JAVA) { LOG.log(Level.FINE, "Failed to apply SNI to SSLSocket", e); skipSNIApplication.set(true); } else { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } return socket; }</code><technical_language>This is necessarily IBM JDK, please improve message</technical_language>

Target:
private Socket applySNI(final Socket socket, String hostname) { if (skipSNIApplication.get()) { LOG.log(Level.FINE, "Skipping application of SNI because JDK is missing setHost() method."); return socket; } if (socket instanceof SSLSocket) { try { Method setHostMethod = AccessController.doPrivileged(new PrivilegedExceptionAction<Method>() { @Override public Method run() throws NoSuchMethodException { return socket.getClass().getMethod("setHost", String.class); } }); setHostMethod.invoke(socket, hostname); LOG.log(Level.FINE, "Applied SNI to socket for host {0}", hostname); } catch (PrivilegedActionException e) { if (e.getCause() instanceof NoSuchMethodException) { Level logLevel = Environment.IS_IBM_JAVA ? Level.FINE : Level.WARNING; LOG.log(logLevel, "Failed to apply SNI to SSLSocket", e); skipSNIApplication.set(true); } else { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { LOG.log(Level.WARNING, "Failed to apply SNI to SSLSocket", e); } } return socket; }
Source:
<code><START> public ActualMeterReads(final Date logTime, final long activeEnergyImport, final long activeEnergyExport, <END> final long activeEnergyImportTariffOne, final long activeEnergyImportTariffTwo, final long activeEnergyExportTariffOne, final long activeEnergyExportTariffTwo, final ScalerUnit scalerUnit) { super(logTime, activeEnergyImport, activeEnergyExport, activeEnergyImportTariffOne, activeEnergyImportTariffTwo, activeEnergyExportTariffOne, activeEnergyExportTariffTwo); this.scalerUnit = scalerUnit; }</code><technical_language>![MAJOR](<LINK_0> Constructor 8 parameters, is greater 7 authorized. [![rule](<LINK_2>](<LINK_1></technical_language>

Target:
public ActualMeterReads(final Date logTime, final long activeEnergyImport, final long activeEnergyExport, final long activeEnergyImportTariffOne, final long activeEnergyImportTariffTwo, final long activeEnergyExportTariffOne, final long activeEnergyExportTariffTwo, final ScalerUnit scalerUnit) { super(logTime, activeEnergyImport, activeEnergyExport, activeEnergyImportTariffOne, activeEnergyImportTariffTwo, activeEnergyExportTariffOne, activeEnergyExportTariffTwo); this.scalerUnit = new ScalerUnit(scalerUnit.getDlmsUnit(), scalerUnit.getScaler()); }
Source:
<code>public void typeProcessingOver() { if (getBooleanOption(COUNT_FRAMEWORK_BUILD_CALLS)) { <START> System.out.printf("Found %d build() method calls.\n", numBuildCalls); <END> } super.typeProcessingOver(); }</code><technical_language>\n in printed output, is portable operating systems. %n instead</technical_language>

Target:
public void typeProcessingOver() { if (getBooleanOption(COUNT_FRAMEWORK_BUILD_CALLS)) { System.out.printf("Found %d build() method calls.%n", numBuildCalls); } super.typeProcessingOver(); }
Source:
<code>protected int checkCommon(int[] hashes, boolean rejoining, VoltTable resultTables[], VoltMessage message, boolean txnSucceed) { if (!rejoining) { if (m_responseHashes == null) { m_responseHashes = hashes; m_txnSucceed = txnSucceed; } <START> else if (DeterminismHash.compareHashes(m_responseHashes, hashes) >= 0) { <END> tmLog.fatal("Stored procedure " + getStoredProcedureName() + " generated different SQL queries at different partitions." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("HASH MISMATCH", hashes, message, DeterminismHash.compareHashes(m_responseHashes, hashes)); return MISMATCH; } else if (m_txnSucceed != txnSucceed) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " succeeded on one partition but failed on another partition." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("PARTIAL ROLLBACK/ABORT", hashes, message, -1); return ABORT; } m_lastResponse = message; m_lastResultTables = resultTables; } if (m_lastResponse == null) { m_lastResponse = message; m_lastResultTables = resultTables; } m_expectedHSIds.remove(message.m_sourceHSId); if (m_expectedHSIds.size() == 0) { return DONE; } else { return WAITING; } }</code><technical_language>compare hash twice, remember return if block. do this: Java int pos; ... else if ((pos = DeterminismHash.compareHashes(m_responseHashes, hashes)) >= 0) { ... logRelevantMismatchInformation("HASH MISMATCH", hashes, message, pos); }</technical_language>

Target:
protected int checkCommon(int[] hashes, boolean rejoining, VoltTable resultTables[], VoltMessage message, boolean txnSucceed) { if (!rejoining) { int pos = -1; if (m_responseHashes == null) { m_responseHashes = hashes; m_txnSucceed = txnSucceed; } else if ((pos = DeterminismHash.compareHashes(m_responseHashes, hashes)) >= 0) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " generated different SQL queries at different partitions." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("HASH MISMATCH", hashes, message, pos); return MISMATCH; } else if (m_txnSucceed != txnSucceed) { tmLog.fatal("Stored procedure " + getStoredProcedureName() + " succeeded on one partition but failed on another partition." + " Shutting down to preserve data integrity."); logRelevantMismatchInformation("PARTIAL ROLLBACK/ABORT", hashes, message, pos); return ABORT; } m_lastResponse = message; m_lastResultTables = resultTables; } if (m_lastResponse == null) { m_lastResponse = message; m_lastResultTables = resultTables; } m_expectedHSIds.remove(message.m_sourceHSId); if (m_expectedHSIds.size() == 0) { return DONE; } else { return WAITING; } }
Source:
<code>private void openConversation(Conversation conversation, Bundle extras) { ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); final boolean mainNeedsRefresh; if (conversationFragment == null) { mainNeedsRefresh = false; Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); if (mainFragment != null && mainFragment instanceof ConversationFragment) { conversationFragment = (ConversationFragment) mainFragment; } else { conversationFragment = new ConversationFragment(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations( R.animator.fade_bottom_in, R.animator.fade_bottom_out, R.animator.fade_bottom_in, R.animator.fade_bottom_out ); <START> fragmentTransaction.replace(R.id.main_fragment, conversationFragment); <END> fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } else { mainNeedsRefresh = true; } conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras); if (mainNeedsRefresh) { refreshFragment(R.id.main_fragment); } else { invalidateActionBarTitle(); } }</code><technical_language>change animation</technical_language>

Target:
private void openConversation(Conversation conversation, Bundle extras) { ConversationFragment conversationFragment = (ConversationFragment) getFragmentManager().findFragmentById(R.id.secondary_fragment); final boolean mainNeedsRefresh; if (conversationFragment == null) { mainNeedsRefresh = false; Fragment mainFragment = getFragmentManager().findFragmentById(R.id.main_fragment); if (mainFragment != null && mainFragment instanceof ConversationFragment) { conversationFragment = (ConversationFragment) mainFragment; } else { conversationFragment = new ConversationFragment(); FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction(); fragmentTransaction.setCustomAnimations( R.animator.fade_in, R.animator.fade_right_out, R.animator.fade_in, R.animator.fade_right_out ); fragmentTransaction.replace(R.id.main_fragment, conversationFragment); fragmentTransaction.addToBackStack(null); fragmentTransaction.commit(); } } else { mainNeedsRefresh = true; } conversationFragment.reInit(conversation, extras == null ? new Bundle() : extras); if (mainNeedsRefresh) { refreshFragment(R.id.main_fragment); } else { invalidateActionBarTitle(); } }
Source:
<code>public void handleEvent(Event event) { if (!initialized) { throw new RuntimeException("JmxJobMBeanManager has not been initialized"); } if (event.getRunner() instanceof JobRunner) { JobRunner jobRunner = (JobRunner) event.getRunner(); ExecutableNode node = jobRunner.getNode(); if (logger.isDebugEnabled()) { <START> logger.info("*** got " + event.getType() + " " + node.getId() + " " <END> + event.getRunner().getClass().getName() + " status: " + node.getStatus()); } if (event.getType() == Event.Type.JOB_STARTED) { runningJobCount.incrementAndGet(); } else if (event.getType() == Event.Type.JOB_FINISHED) { totalExecutedJobCount.incrementAndGet(); if (runningJobCount.intValue() > 0) { runningJobCount.decrementAndGet(); } else { logger.warn("runningJobCount not messed up, it is already zero " + "and we are trying to decrement on job event " + Event.Type.JOB_FINISHED); } if (node.getStatus() == Status.FAILED) { totalFailedJobCount.incrementAndGet(); } else if (node.getStatus() == Status.SUCCEEDED) { totalSucceededJobCount.incrementAndGet(); } handleJobFinishedCount(node.getStatus(), node.getType()); } } else { logger.warn("((((((((( Got a different runner: " + event.getRunner().getClass().getName()); } }</code><technical_language>logger.debug</technical_language>

Target:
public void handleEvent(Event event) { if (!initialized) { throw new RuntimeException("JmxJobMBeanManager has not been initialized"); } if (event.getRunner() instanceof JobRunner) { JobRunner jobRunner = (JobRunner) event.getRunner(); ExecutableNode node = jobRunner.getNode(); if (logger.isDebugEnabled()) { logger.debug("*** got " + event.getType() + " " + node.getId() + " " + event.getRunner().getClass().getName() + " status: " + node.getStatus()); } if (event.getType() == Event.Type.JOB_STARTED) { runningJobCount.incrementAndGet(); } else if (event.getType() == Event.Type.JOB_FINISHED) { totalExecutedJobCount.incrementAndGet(); if (runningJobCount.intValue() > 0) { runningJobCount.decrementAndGet(); } else { logger.warn("runningJobCount not messed up, it is already zero " + "and we are trying to decrement on job event " + Event.Type.JOB_FINISHED); } if (node.getStatus() == Status.FAILED) { totalFailedJobCount.incrementAndGet(); } else if (node.getStatus() == Status.SUCCEEDED) { totalSucceededJobCount.incrementAndGet(); } handleJobFinishedCount(node.getStatus(), node.getType()); } } else { logger.warn("((((((((( Got a different runner: " + event.getRunner().getClass().getName()); } }
Source:
<code>public void setMaskPattern(String pattern) { try { maskPattern = Pattern.compile(pattern); } catch (Exception e) { <START> logger.error("Error to compile regex for mask pattern, will not mask anything", e); <END> } }</code><technical_language>include incorrect pattern</technical_language>

Target:
public void setMaskPattern(String pattern) { try { maskPattern = Pattern.compile(pattern); } catch (Exception e) { logger.error("Error to compile regex for mask pattern, will not mask anything. Invalid pattern: " + pattern, e); } }
Source:
<code>private GoalConflictMessage sendOrUpdateConflictMessage(PotentialConflictDTO payload, Set<Goal> conflictingGoalsOfUser, MessageDestination destination) { Date now = new Date(); Date minEndTime = new Date(now.getTime() - conflictInterval); Goal conflictingGoal = conflictingGoalsOfUser.iterator().next(); GoalConflictMessage message = cacheService.fetchLatestGoalConflictMessageForUser(payload.getLoginID(), conflictingGoal.getID(), destination, minEndTime); if (message == null || message.getEndTime().before(minEndTime)) { message = GoalConflictMessage.createInstance(payload.getLoginID(), conflictingGoal, payload.getURL()); <START> destination.send(message); <END> } else if (now.getTime() - message.getEndTime().getTime() >= updateSkipWindow) { assert payload.getLoginID().equals(message.getRelatedLoginID()); assert conflictingGoal.getID().equals(message.getGoal().getID()); message.setEndTime(now); } else { return message; } cacheService.updateLatestGoalConflictMessageForUser(message, destination); return message; }</code><technical_language>Move this sendNewGoalConflictMessage</technical_language>

Target:
private GoalConflictMessage sendOrUpdateConflictMessage(PotentialConflictDTO payload, Set<Goal> conflictingGoalsOfUser, MessageDestination destination) { Date now = new Date(); Date minEndTime = new Date(now.getTime() - conflictInterval); Goal conflictingGoal = conflictingGoalsOfUser.iterator().next(); GoalConflictMessage message = cacheService.fetchLatestGoalConflictMessageForUser(payload.getLoginID(), conflictingGoal.getID(), destination, minEndTime); if (message == null || message.getEndTime().before(minEndTime)) { message = sendNewGoalConflictMessage(payload, conflictingGoal, destination); cacheService.updateLatestGoalConflictMessageForUser(message, destination); } else if (now.getTime() - message.getEndTime().getTime() >= updateSkipWindow) { updateLastGoalConflictMessage(payload, now, conflictingGoal, message); cacheService.updateLatestGoalConflictMessageForUser(message, destination); } return message; }
Source:
<code>private long sumOfChangelogOffsets(final TaskId id, final Map<TopicPartition, Long> changelogOffsets) { long offsetSum = 0L; for (final Map.Entry<TopicPartition, Long> changelogEntry : changelogOffsets.entrySet()) { final long offset = changelogEntry.getValue(); <START> if (offset == Task.LATEST_OFFSET) { <END> return Task.LATEST_OFFSET; } else { offsetSum += offset; if (offsetSum < 0) { log.warn("Sum of changelog offsets for task overflowed, pinning to Long.MAX_VALUE", id); return Long.MAX_VALUE; } } } return offsetSum; }</code><technical_language>check task.isActive here</technical_language>

Target:
private long sumOfChangelogOffsets(final TaskId id, final Map<TopicPartition, Long> changelogOffsets) { long offsetSum = 0L; for (final Map.Entry<TopicPartition, Long> changelogEntry : changelogOffsets.entrySet()) { final long offset = changelogEntry.getValue(); if (offset == Task.LATEST_OFFSET) { return Task.LATEST_OFFSET; } else { if (offset < 0) { throw new IllegalStateException("Offset should not be negative."); } offsetSum += offset; if (offsetSum < 0) { log.warn("Sum of changelog offsets for task overflowed, pinning to Long.MAX_VALUE", id); return Long.MAX_VALUE; } } } return offsetSum; }
Source:
<code>private TaskExecutor createTaskExecutor(TaskManagerServices taskManagerServices, HeartbeatServices heartbeatServices, TaskExecutorPartitionTracker taskExecutorPartitionTracker) { return new TaskExecutor( rpc, TaskManagerConfiguration.fromConfiguration(configuration, TM_RESOURCE_SPEC), haServices, taskManagerServices, <START> ExternalResourceInfoProvider.EMPTY_PROVIDER, <END> heartbeatServices, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), null, dummyBlobCacheService, testingFatalErrorHandler, taskExecutorPartitionTracker, TaskManagerRunner.createBackPressureSampleService(configuration, rpc.getScheduledExecutor())); }</code><technical_language>rename suggestion ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES,</technical_language>

Target:
private TaskExecutor createTaskExecutor(TaskManagerServices taskManagerServices, HeartbeatServices heartbeatServices, TaskExecutorPartitionTracker taskExecutorPartitionTracker) { return new TaskExecutor( rpc, TaskManagerConfiguration.fromConfiguration( configuration, TM_RESOURCE_SPEC, InetAddress.getLoopbackAddress().getHostAddress()), haServices, taskManagerServices, ExternalResourceInfoProvider.NO_EXTERNAL_RESOURCES, heartbeatServices, UnregisteredMetricGroups.createUnregisteredTaskManagerMetricGroup(), null, dummyBlobCacheService, testingFatalErrorHandler, taskExecutorPartitionTracker, TaskManagerRunner.createBackPressureSampleService(configuration, rpc.getScheduledExecutor())); }
Source:
<code>public List<ProjectData> call() throws OrmException { final List<ProjectData> result = new ArrayList<ProjectData>(); for(final Project p : db.projects().all().toList()) { boolean canBeDeleted = false; <START> final List<Change> changes = db.changes().byProjectHaschange(p.getNameKey()).toList(); <END> try { final ProjectControl c = projectControlFactory.controlFor(p.getNameKey()); if (c.isVisible() || c.isOwner()) { if (c.isOwner() && changes.size() == 0) { canBeDeleted = true; } final ProjectData projectData = new ProjectData(p.getNameKey(), p.getDescription(), canBeDeleted); result.add(projectData); } } catch (NoSuchProjectException e) { continue; } } Collections.sort(result, new Comparator<ProjectData>() { public int compare(final ProjectData a, final ProjectData b) { return a.getName().compareTo(b.getName()); } }); return result; }</code><technical_language>Is this a sufficient test empty? if a project commits in more branches pushed project bypassed code review? project a gerrit server review feature. I if require project truely empty. is: * changes * zero refs in repository * * single ref single commit parents empty tree tree (so files)</technical_language>

Target:
public List<ProjectData> call() throws OrmException, RepositoryNotFoundException { final List<ProjectData> result = new ArrayList<ProjectData>(); for(final Project p : db.projects().all().toList()) { boolean canBeDeleted = false; try { final ProjectControl c = projectControlFactory.controlFor(p.getNameKey()); if (c.isVisible() || c.isOwner()) { if (c.isOwner() && (!c.getProjectState().isSpecialWildProject())) { try { final Repository repo = repoManager.openRepository(p.getName()); final Map<String, Ref> refs = repo.getAllRefs(); repo.close(); if (refs.isEmpty()) { canBeDeleted = true; } } catch (RepositoryNotFoundException e) { log.error("Repository " + p.getName() + " was not found"); } } result.add(new ProjectData(p.getNameKey(), p.getDescription(), canBeDeleted)); } } catch (NoSuchProjectException e) { continue; } } Collections.sort(result, new Comparator<ProjectData>() { public int compare(final ProjectData a, final ProjectData b) { return a.getName().compareTo(b.getName()); } }); return result; }
Source:
<code>public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); final OutputStream out = storage.create(filename, true); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } finally { try { close(); } catch (Throwable t) { <START> log.error("Could not close Record Writer", t); <END> } } } @Override public void close() { try { writer.close(); } catch (IOException e) { throw new DataException(e); } } @Override public void commit() }; }</code><technical_language>want verify in a scratch area DataException thrown. I do recall exception finally block override caught finally block, I recall if finally block catches it</technical_language>

Target:
public io.confluent.connect.storage.format.RecordWriter getRecordWriter( final HdfsSinkConnectorConfig conf, final String filename ) { return new io.confluent.connect.storage.format.RecordWriter() { final DataFileWriter<Object> writer = new DataFileWriter<>(new GenericDatumWriter<>()); Schema schema = null; @Override public void write(SinkRecord record) { if (schema == null) { schema = record.valueSchema(); try { log.info("Opening record writer for: {}", filename); final OutputStream out = storage.create(filename, true); org.apache.avro.Schema avroSchema = avroData.fromConnectSchema(schema); writer.setCodec(CodecFactory.fromString(conf.getAvroCodec())); writer.create(avroSchema, out); } catch (IOException e) { throw new ConnectException(e); } } log.trace("Sink record: {}", record); Object value = avroData.fromConnectData(schema, record.value()); try { if (value instanceof NonRecordContainer) { writer.append(((NonRecordContainer) value).getValue()); } else { writer.append(value); } } catch (IOException e) { throw new DataException(e); } } @Override public void close() { try { writer.close(); } catch (IOException e) { throw new DataException(e); } } @Override public void commit() }; }
Source:
<code>private void showOnboardingInstruction() { <START> InstructionDialogFragment.newInstance( <END> onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME, true).show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }</code><technical_language>pulling instructionType int a variable in line for readability. optional suggestion</technical_language>

Target:
private void showOnboardingInstruction() { int instructionType = onboardingHelper.isDefaultBrowserFirefox() ? InstructionDialogFragment.EXTRA_INSTRUCTION_FIREFOX : InstructionDialogFragment.EXTRA_INSTRUCTION_CHROME; InstructionDialogFragment.newInstance(instructionType, true) .show(getSupportFragmentManager(), InstructionDialogFragment.TAG); }