auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testRemoveModifiedFileWithSTRICT() throws Exception { try { runner.applyPatch(zippedPatch, ContentVerificationPolicy.STRICT); <START> fail("Patch shouldn't be applied - ContentVerificationPolicy.STRICT"); <END> } catch (ContentConflictsException e) { assertPatchHasNotBeenApplied(e, patch, fileRemoved.getItem(), env); assertFileExists(removedFile); assertArrayEquals(expectedModifiedHash, hashFile(removedFile)); } }</code><technical_language>This is a functional change in a separate PR</technical_language>

Target:
public void testRemoveModifiedFileWithSTRICT() throws Exception { try { runner.applyPatch(zippedPatch, ContentVerificationPolicy.STRICT); } catch (ContentConflictsException e) { assertPatchHasNotBeenApplied(e, patch, fileRemoved.getItem(), env); assertFileExists(removedFile); assertArrayEquals(expectedModifiedHash, hashFile(removedFile)); } }
Source:
<code>CosmosPermissionProperties(String jsonString) { this.permission = new Permission(jsonString); this.permissionName = permission.getId(); this.permissionMode = permission.getPermissionMode(); this.resourcePartitionKey = permission.getResourcePartitionKey(); this.resourceToken = permission.getToken(); <START> String[] parts = Utils.trimBeginningAndEndingSlashes(permission.getResourceLink()).split("/"); <END> if (parts.length < 4) { throw new IllegalArgumentException("jsonString"); } this.databaseName = parts[1]; this.containerName = parts[3]; if (parts.length >= 6) { this.resourceName = parts[5]; if (Paths.DOCUMENTS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.ITEM; } else if (Paths.STORED_PROCEDURES_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.STORED_PROCEDURE; } else if (Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.USER_DEFINED_FUNCTION; } else if (Paths.TRIGGERS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = CosmosContainerChildResourceKind.TRIGGER; } else { throw new IllegalArgumentException("jsonString"); } } }</code><technical_language>please StringUtils.split instead of String.split String.split regex is performant</technical_language>

Target:
CosmosPermissionProperties(String jsonString) { this.permission = new Permission(jsonString); this.permissionName = permission.getId(); this.permissionMode = permission.getPermissionMode(); this.resourcePartitionKey = permission.getResourcePartitionKey(); this.resourceToken = permission.getToken(); String[] parts = StringUtils.split(Utils.trimBeginningAndEndingSlashes(permission.getResourceLink()), "/"); if (parts.length < 4) { throw new IllegalArgumentException("jsonString"); } this.databaseName = parts[1]; this.containerName = parts[3]; if (parts.length >= 6) { this.resourceName = parts[5]; if (Paths.DOCUMENTS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.ITEM; } else if (Paths.STORED_PROCEDURES_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.STORED_PROCEDURE; } else if (Paths.USER_DEFINED_FUNCTIONS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.USER_DEFINED_FUNCTION; } else if (Paths.TRIGGERS_PATH_SEGMENT.equalsIgnoreCase(parts[4])) { this.resourceKind = ContainerChildResourceType.TRIGGER; } else { throw new IllegalArgumentException("jsonString"); } } }
Source:
<code>public LinkedList<StreamAppDefinition> getAppDefinitions() { <START> if (this.applicationDefinitions == null || this.applicationDefinitions.isEmpty()) { <END> return getAppDefinitions(this.name, this.dslText); } return this.applicationDefinitions; }</code><technical_language>Consider CollectionUtils.isEmpty(this.applicationDefinitions) instead</technical_language>

Target:
public LinkedList<StreamAppDefinition> getAppDefinitions() { if (CollectionUtils.isEmpty(this.applicationDefinitions)) { return getAppDefinitions(this.name, this.dslText); } return this.applicationDefinitions; }
Source:
<code>protected void onPreExecute() { super.onPreExecute(); <START> if (contextWeakReference.get() == null) { <END> return; } String title = contextWeakReference.get().getString(R.string.please_wait); String message = contextWeakReference.get().getString(R.string.loading); progressDialog = ProgressDialog.show(contextWeakReference.get(), title, message); }</code><technical_language>Please read correct usage of WeakReference. get() returns a regular reference, true, save this returned somewhere, WeakReference hold prevent garbage collector collecting context weak reference points to. introduce a new local var, write result of contextWeakReference.get() this regular reference for remainder of this method. risk running a NPE</technical_language>

Target:
protected void onPreExecute() { Context context = contextWeakReference.get(); if (context == null) { return; } String title = context.getString(R.string.please_wait); String message = context.getString(R.string.loading); progressDialog = ProgressDialog.show(context, title, message); }
Source:
<code>protected Properties addConnectionProperties(Properties properties) { Set<String> configKeys = config.values().keySet(); <START> config.originalsWithPrefix("connection.").forEach((k,v) -> { <END> if (!configKeys.contains("connection." + k)) { properties.put(k, v); } }); return properties; }</code><technical_language>Pull "connection." private static final</technical_language>

Target:
protected Properties addConnectionProperties(Properties properties) { Set<String> configKeys = config.values().keySet(); config.originalsWithPrefix(JdbcSourceConnectorConfig.CONNECTION_PREFIX).forEach((k,v) -> { if (!configKeys.contains(JdbcSourceConnectorConfig.CONNECTION_PREFIX + k)) { properties.put(k, v); } }); return properties; }
Source:
<code>public Response createWorkflowInstance( @Valid @ApiParam(value = "Submitted workflow instance information", required = true) CreateWorkflowInstanceRequest req) { WorkflowInstance instance = createWorkflowConverter.convert(req); try { long id = workflowInstances.insertWorkflowInstance(instance); instance = workflowInstances.getWorkflowInstance(id, EnumSet.of(WorkflowInstanceInclude.CURRENT_STATE_VARIABLES), null); return created(URI.create(String.valueOf(id))).entity(createWorkflowConverter.convert(instance)).build(); } catch (StateVariableValueTooLongException e) { <START> return status(BAD_REQUEST.getStatusCode(), e.getMessage()).build(); <END> } }</code><technical_language>throw StateVariableValueTooLongException out add exceptionmapper instead</technical_language>

Target:
public Response createWorkflowInstance( @Valid @ApiParam(value = "Submitted workflow instance information", required = true) CreateWorkflowInstanceRequest req) { WorkflowInstance instance = createWorkflowConverter.convert(req); long id = workflowInstances.insertWorkflowInstance(instance); instance = workflowInstances.getWorkflowInstance(id, EnumSet.of(WorkflowInstanceInclude.CURRENT_STATE_VARIABLES), null); return created(URI.create(String.valueOf(id))).entity(createWorkflowConverter.convert(instance)).build(); }
Source:
<code>public static void initializeBeanInstance(Object instance) { Collection<Method> postConstructMethods = collectPostConstructMethods(instance.getClass()); for (Method method : postConstructMethods) { LOG.debug("invoking post-construct method {}", method); try { method.setAccessible(true); <START> method.invoke(instance); <END> } catch (Exception e) { throw translateException("Exception while invoking @PostConstruct method {}", e); } } Collection<Field> fields = collectInjectedFields(instance.getClass()); for (Field field : fields) { LOG.debug("injecting field {}", field); try { field.setAccessible(true); Object value = BEANS.get(field.getType()); field.set(instance, value); } catch (Exception e) { throw translateException("Exception while injecting field", e); } } }</code><technical_language>Calling @PostConstruct methods step of initialization injection code run</technical_language>

Target:
public static void initializeBeanInstance(Object instance) { Collection<Field> fields = collectInjectedFields(instance.getClass()); for (Field field : fields) { LOG.debug("injecting field {}", field); try { field.setAccessible(true); Object value = BEANS.get(field.getType()); field.set(instance, value); } catch (Exception e) { throw translateException("Exception while injecting field", e); } } Collection<Method> initMethods = collectInjectedMethods(instance.getClass()); for (Method method : initMethods) { LOG.debug("invoking injected method {}", method); try { method.setAccessible(true); method.invoke(instance, BeanInstanceUtil.getInjectionArguments(method.getParameterTypes())); } catch (Exception e) { throw translateException("Exception while invoking @InjectBean method", e); } } Collection<Method> postConstructMethods = collectPostConstructMethods(instance.getClass()); for (Method method : postConstructMethods) { LOG.debug("invoking post-construct method {}", method); try { method.setAccessible(true); method.invoke(instance); } catch (Exception e) { throw translateException("Exception while invoking @PostConstruct method {}", e); } } }
Source:
<code>abstract <S extends KeySpec> S getKeySpec(final Class<S> keySpecType) throws InvalidKeySpecException; abstract boolean verify(final char[] guess) throws InvalidKeyException; boolean verify(final char[] guess, Charset hashCharset) throws InvalidKeyException { <START> throw new InvalidKeyException(); <END> }</code><technical_language>This UnsupportedOperationException</technical_language>

Target:
abstract <S extends KeySpec> S getKeySpec(final Class<S> keySpecType) throws InvalidKeySpecException; abstract boolean verify(final char[] guess) throws InvalidKeyException; boolean verify(final char[] guess, Charset hashCharset) throws InvalidKeyException { throw new UnsupportedOperationException(); }
Source:
<code><START> public Hole(Element element) { <END> super(element); this.sort = KSorts.KITEM; }</code><technical_language>fight this, I time work new kast, location information completely redone</technical_language>

Target:
public Hole(Element element) { super(element); this.sort = Sort.KITEM; }
Source:
<code>protected void autoFillNameTextField() { <START> setAccountNameWithString(accountIdInputTextField.getText().trim()); <END> }</code><technical_language>is necessary anymore other PR merged already</technical_language>

Target:
protected void autoFillNameTextField() { setAccountNameWithString(accountIdInputTextField.getText()); }
Source:
<code>public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { if(this.offHeapResourceIdentifiers.isEmpty()) { return responseFactory.failure( <START> new IllegalStateException("Server started without any offheap resources defined." + <END> " Check your server configuration and define at least one offheap resource.") ); } try { switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(e); } }</code><technical_language>ResourceConfigurationException sounds me. stop form of RuntimeException wire, please. a pain handle client side</technical_language>

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusteredEhcacheException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(e); } }
Source:
<code>public void updateProgressBar(int id, int value) { super.updateProgressBar(id, value); switch (id) { case 0: inventory.fill = value != 0; <START> ((GuiBase) ClientProxy.getOpenGui()).redraw(); <END> break; case 1: if (value >= 0) inventory.tank.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.tank.getFluidAmount())); else inventory.tank.setFluid(null); break; case 2: if (value > 0 && inventory.tank.getFluid() != null) inventory.tank.setFluid(new FluidStack(inventory.tank.getFluid(), value)); else inventory.tank.setFluid(null); break; default: break; } }</code><technical_language>Please add 'instanceof GuiBase' check here, know..</technical_language>

Target:
public void updateProgressBar(int id, int value) { super.updateProgressBar(id, value); switch (id) { case 0: inventory.fill = value != 0; redrawOpenGui(); break; case 1: if (value >= 0) inventory.tank.setFluid(new FluidStack(FluidRegistry.getFluid(value), inventory.tank.getFluidAmount())); else inventory.tank.setFluid(null); break; case 2: if (value > 0 && inventory.tank.getFluid() != null) inventory.tank.setFluid(new FluidStack(inventory.tank.getFluid(), value)); else inventory.tank.setFluid(null); break; default: break; } }
Source:
<code>public ValidationResult validUseDefaultNetworkFilterFlag(boolean useDefaultNetworkFilterId) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_INVALID_VNIC_PROFILE_NETWORK_ID_CONFIGURATION, ReplacementUtils.createSetVariableString(VAR_VNIC_PROFILE_NAME, vnicProfile.getName()), ReplacementUtils.createSetVariableString(VAR_NETWORK_FILTER_ID, vnicProfile.getNetworkFilterId())) <START> .when(useDefaultNetworkFilterId & vnicProfile.getNetworkFilterId() != null); <END> }</code><technical_language>Please && Done</technical_language>

Target:
public ValidationResult validUseDefaultNetworkFilterFlag(boolean useDefaultNetworkFilterId) { return ValidationResult.failWith(EngineMessage.ACTION_TYPE_FAILED_INVALID_VNIC_PROFILE_NETWORK_ID_CONFIGURATION, ReplacementUtils.createSetVariableString(VAR_VNIC_PROFILE_NAME, vnicProfile.getName()), ReplacementUtils.createSetVariableString(VAR_NETWORK_FILTER_ID, vnicProfile.getNetworkFilterId())) .when(useDefaultNetworkFilterId && vnicProfile.getNetworkFilterId() != null); }
Source:
<code>public void open() throws ConnectionException, XBeeDeviceException, TimeoutException { logger.info("Opening the connection interface..."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); <START> logger.info("Connection interface open."); <END> dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineConnectionMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException("Unsupported operating mode: AT."); } }</code><technical_language>I doubts here... is 'open' 'opened'</technical_language>

Target:
public void open() throws ConnectionException, XBeeDeviceException, TimeoutException { logger.info(toString() + "Opening the connection interface..."); if (connectionInterface.isOpen()) throw new InterfaceAlreadyOpenException(); connectionInterface.open(); logger.info(toString() + "Connection interface open."); dataReader = new DataReader(connectionInterface, operatingMode); dataReader.start(); if (operatingMode == OperatingMode.UNKNOWN) operatingMode = determineConnectionMode(); if (operatingMode == OperatingMode.UNKNOWN) { close(); throw new InvalidOperatingModeException("Could not determine operating mode."); } else if (operatingMode == OperatingMode.AT) { close(); throw new InvalidOperatingModeException(operatingMode); } }
Source:
<code>void updateResourcePermissionsById(String resourceId) throws UserStoreException { Connection dbConnection = null; ResultSet rs = null; PreparedStatement statement = null; try { PermissionTree tree = new PermissionTree(); tree.root = this.root; dbConnection = getDBConnection(); if (preserveCaseForResources) { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID_CASE_SENSITIVE); } else { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID); } statement.setInt(1, tenantId); statement.setInt(2, tenantId); statement.setString(3, resourceId); rs = statement.executeQuery(); write.lock(); try { while (rs.next()) { short allow = rs.getShort(3); String roleName = rs.getString(1); String domain = rs.getString(5); String roleWithDomain = UserCoreUtil.addDomainToName(roleName, domain); if (allow == UserCoreConstants.ALLOW) { tree.authorizeRoleInTree(roleWithDomain, rs.getString(2), rs.getString(4), false); } } } finally { write.unlock(); } write.lock(); try { <START> this.root = tree.root; <END> } finally { write.unlock(); } } catch (SQLException e) { throw new UserStoreException( "Error loading authorizations. Please check the database. Error message is " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, statement); } }</code><technical_language>nt this line 1062. separate write.lock() race conditions</technical_language>

Target:
void updateResourcePermissionsById(String resourceId) throws UserStoreException { Connection dbConnection = null; ResultSet rs = null; PreparedStatement statement = null; try { PermissionTree tree = new PermissionTree(); tree.root = this.root; dbConnection = getDBConnection(); if (preserveCaseForResources) { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID_CASE_SENSITIVE); } else { statement = dbConnection.prepareStatement(DBConstants.GET_EXISTING_ROLE_PERMISSIONS_BY_RESOURCE_ID); } statement.setInt(1, tenantId); statement.setInt(2, tenantId); statement.setString(3, resourceId); rs = statement.executeQuery(); write.lock(); try { while (rs.next()) { short allow = rs.getShort(3); String roleName = rs.getString(1); String domain = rs.getString(5); String roleWithDomain = UserCoreUtil.addDomainToName(roleName, domain); if (allow == UserCoreConstants.ALLOW) { tree.authorizeRoleInTree(roleWithDomain, rs.getString(2), rs.getString(4), false); } } } finally { this.root = tree.root; write.unlock(); } } catch (SQLException e) { throw new UserStoreException( "Error loading authorizations. Please check the database. Error message is " + e.getMessage(), e); } finally { DatabaseUtil.closeAllConnections(dbConnection, rs, statement); } }
Source:
<code>public List<Widget> getGroupWidgetsConfig(@PathVariable String uuid) { <START> Optional<Group> group = repositoryService.getGroup(uuid); <END> if (group.isPresent()) { return group.get().getWidgets(); } else { throw new SQCompanionException("Can't find requested group uuid: " + uuid); } }</code><technical_language>return repositoryService.getGroup(uuid).map(Group::getWidgets).orElseThrow(() -> SQCompanionException) ? ;-)</technical_language>

Target:
public List<Widget> getGroupWidgetsConfig(@PathVariable String uuid) { return repositoryService.getGroup(uuid).map(Group::getWidgets).orElseThrow(() -> new SQCompanionException("Can't find requested group uuid: " + uuid)); }
Source:
<code><START> public static FingerprintStorage get(){ <END> String fingerprintStorageEngine = SystemProperties.getString("FingerprintStorageEngine", "jenkins.fingerprints.FileFingerprintStorage"); return ExtensionList.lookup(FingerprintStorage.class).getDynamic(fingerprintStorageEngine); }</code><technical_language>nit: space get() {</technical_language>

Target:
public static FingerprintStorage get() { return ExtensionList.lookup(FingerprintStorage.class).get(0); }
Source:
<code>public static void onKnockBack(LivingKnockBackEvent event) { <START> if(event.getEntityLiving() instanceof EntitySheep) <END> { event.setCanceled(true); } }</code><technical_language>this mod disabled default</technical_language>

Target:
public static void onKnockBack(LivingKnockBackEvent event) { if(ENABLED) { if(event.getEntityLiving() instanceof EntitySheep) { event.setStrength(0.2F); } else if(event.getEntityLiving() instanceof EntityCow) { event.setCanceled(true); } } }
Source:
<code>private XSSFRow getRow(XSSFSheet sheet,int index) <START> { <END> if(sheet.getRow(index)!=null) return sheet.getRow(index); else return sheet.createRow(index); }</code><technical_language>Open { end of previous line</technical_language>

Target:
private XSSFRow getRow(XSSFSheet sheet,int index){ if (sheet.getRow(index) != null) { return sheet.getRow(index); } else { return sheet.createRow(index); } }
Source:
<code>public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; <START> setShellStyle(getShellStyle() | SWT.RESIZE); <END> }</code><technical_language>if do in AvdCreationDialog, mind adding SWT.SWAP force-relayout thing? A call getShell().layout(true, true)) changing text force wrap properly, expect label behave in place</technical_language>

Target:
public GridDialog(Shell parentShell, int numColumns, boolean makeColumnsEqualWidth) { super(parentShell); mNumColumns = numColumns; mMakeColumnsEqualWidth = makeColumnsEqualWidth; }
Source:
<code>private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { if (validatorDir.canRead() && validatorDir.isDirectory()) { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); if (resourceTimestamps.get(f.getName()) == null || resourceTimestamps.get(f.getName()) != f.lastModified()) { reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { try { if (validatorLoader != null) { validatorLoader.close(); } } catch (IOException e) { <START> logger.error("Cannot reload validator classloader."); <END> throw new ValidatorManagerException(e); } validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }</code><technical_language>I good include "Failed close validator classloader." in logged error message</technical_language>

Target:
private void checkResources() { File validatorDir = new File(validatorDirPath); List<URL> resources = new ArrayList<URL>(); boolean reloadResources = false; try { if (validatorDir.canRead() && validatorDir.isDirectory()) { for (File f : validatorDir.listFiles()) { if (f.getName().endsWith(".jar")) { resources.add(f.toURI().toURL()); if (resourceTimestamps.get(f.getName()) == null || resourceTimestamps.get(f.getName()) != f.lastModified()) { reloadResources = true; logger.info("Resource " + f.getName() + " is updated. Reload the classloader."); resourceTimestamps.put(f.getName(), f.lastModified()); } } } } } catch (MalformedURLException e) { throw new ValidatorManagerException(e); } if (reloadResources) { try { if (validatorLoader != null) { validatorLoader.close(); } } catch (IOException e) { logger.error("Cannot reload validator classloader because failure " + "to close the validator classloader."); } validatorLoader = new URLClassLoader(resources.toArray(new URL[resources.size()])); } }
Source:
<code>public void register() { phaser.register(); <START> try { <END> noSafePoint.check(); } catch (InvalidAssumptionException e) { phaser.arriveAndAwaitAdvance(); try { noSafePoint.check(); } catch (InvalidAssumptionException e1) { phaser.arriveAndAwaitAdvance(); } } }</code><technical_language>@daumayr I I full logic here. situations: - register while safepoint is done - register while safepoint is starting - register while safepoint is in progress distinguish two? transitionsInProgress, no</technical_language>

Target:
public void register() { phaser.register(); }
Source:
<code>public static synchronized void removeIterator(final CtfTmfTrace trace, final CtfTmfContext ctx) { <START> map.get(trace).removeIterator(ctx); <END> }</code><technical_language>if a lingering context disposed trace is disposed. a null check return of get()</technical_language>

Target:
public static synchronized void removeIterator(final CtfTmfTrace trace, final CtfTmfContext ctx) { CtfTraceManager traceManager = map.get(trace); if (traceManager != null) { traceManager.removeIterator(ctx); } }
Source:
<code>public boolean releaseLock(String lockId) { <START> log.warn("A following key are going to be released via external call, keyId : " + lockId); <END> globalLock.lock(); try { InternalLockView lock = locks.get(lockId); if (lock == null) { log.warn("A lock with id : " + lockId + " is not exist and can not be release via external call"); return false; } if (lock.getExclusive()) { releaseExclusiveLock(lockId); } else { releaseSharedLock(lockId); } releasedLock.signal(); } finally { globalLock.unlock(); } log.warn("A following key was released via external call, keyId : " + lockId); return true; }</code><technical_language>message be: "The lock is released external call, lockId {0} " , lockId</technical_language>

Target:
public boolean releaseLock(String lockId) { log.warnFormat("The following lock is going to be released via external call, lockId {0} ", lockId); globalLock.lock(); try { InternalLockView lock = locks.get(lockId); if (lock == null) { log.warnFormat("Lock with id {0} does not exist and can not be released via external call", lockId); return false; } if (lock.getExclusive()) { releaseExclusiveLock(lockId); } else { releaseSharedLock(lockId); } releasedLock.signal(); } finally { globalLock.unlock(); } log.warnFormat("Lock {0} was released via external call", lockId); return true; }
Source:
<code>private void cleanZombieTasks() { long maxTime = DateTime.getNow() .AddMinutes((-1) * Config.<Integer> GetValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMAsyncTask task : _tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getaction_type().toString()); <START> logable.addCustomValue("Dat)e", task.getParameters().getDbAsyncTask().getStartTime().toString()); <END> if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { AuditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Stopping async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.stopTask(true); } else { AuditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Clearing async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.clearAsyncTask(true); } } } }</code><technical_language>please remove ): Da)te = Date</technical_language>

Target:
private void cleanZombieTasks() { long maxTime = DateTime.getNow() .AddMinutes((-1) * Config.<Integer> GetValue(ConfigValues.AsyncTaskZombieTaskLifeInMinutes)).getTime(); for (SPMAsyncTask task : _tasks.values()) { if (task.getParameters().getDbAsyncTask().getStartTime().getTime() < maxTime) { AuditLogableBase logable = new AuditLogableBase(); logable.addCustomValue("CommandName", task.getParameters().getDbAsyncTask().getaction_type().toString()); logable.addCustomValue("Date", task.getParameters().getDbAsyncTask().getStartTime().toString()); if (task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.finished && task.getLastTaskStatus().getStatus() != AsyncTaskStatusEnum.unknown) { AuditLogDirector.log(logable, AuditLogType.TASK_STOPPING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Stopping async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.stopTask(true); } else { AuditLogDirector.log(logable, AuditLogType.TASK_CLEARING_ASYNC_TASK); log.infoFormat("Cleaning zombie tasks: Clearing async task {0} that started at {1}", task.getParameters().getDbAsyncTask().getaction_type(), task .getParameters().getDbAsyncTask().getStartTime()); task.clearAsyncTask(true); } } } }
Source:
<code>private boolean isDowngradeChangesFormats(List<StorageDomainStatic> poolDomains) { <START> List<Object> problematicDomains = new LinkedList<>(); <END> for (StorageDomainStatic domainStatic : poolDomains) { if (VersionStorageFormatUtil.getPreferredForVersion(getStoragePool().getcompatibility_version(), domainStatic.getStorageType()).compareTo( domainStatic.getStorageFormat()) < 0 ) { problematicDomains.add(domainStatic.getStorageName()); } } if (!problematicDomains.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DECREASING_COMPATIBILITY_VERSION_CAUSES_STORAGE_FORMAT_DOWNGRADING); addCanDoActionMessageListVariable("problematicDomains", problematicDomains); return true; } return false; }</code><technical_language>a List<String>, no</technical_language>

Target:
private boolean isDowngradeChangesFormats(List<StorageDomainStatic> poolDomains) { List<String> problematicDomains = new LinkedList<>(); Version storagePoolVersion = getStoragePool().getcompatibility_version(); for (StorageDomainStatic domainStatic : poolDomains) { if (VersionStorageFormatUtil.getPreferredForVersion(storagePoolVersion, domainStatic.getStorageType()).compareTo( domainStatic.getStorageFormat()) < 0 ) { problematicDomains.add(domainStatic.getStorageName()); } } if (!problematicDomains.isEmpty()) { addCanDoActionMessage(VdcBllMessages.ACTION_TYPE_FAILED_DECREASING_COMPATIBILITY_VERSION_CAUSES_STORAGE_FORMAT_DOWNGRADING); getReturnValue().getCanDoActionMessages() .addAll(ReplacementUtils.replaceWith("problematicDomains", problematicDomains, ",")); return true; } return false; }
Source:
<code>protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); <START> VmTemplate originalTemplate = DbFacade.getInstance().getVmTemplateDao().get(getVm().getOriginalTemplateGuid()); <END> if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }</code><technical_language>worth extra code, this is optimization, also, for empty guid, blank template name, i dont want hard code</technical_language>

Target:
protected void addVmStatic() { logImportEvents(); getVm().getStaticData().setId(getVmId()); getVm().getStaticData().setCreationDate(new Date()); getVm().getStaticData().setVdsGroupId(getParameters().getVdsGroupId()); getVm().getStaticData().setMinAllocatedMem(computeMinAllocatedMem()); getVm().getStaticData().setQuotaId(getParameters().getQuotaId()); if (getVm().getOriginalTemplateGuid() != null && !VmTemplateHandler.BlankVmTemplateId.equals(getVm().getOriginalTemplateGuid())) { VmTemplate originalTemplate = getVmTemplateDAO().get(getVm().getOriginalTemplateGuid()); if (originalTemplate != null) { getVm().getStaticData().setOriginalTemplateName(originalTemplate.getName()); } } if (getParameters().getCopyCollapse()) { getVm().setVmtGuid(VmTemplateHandler.BlankVmTemplateId); } getVmStaticDAO().save(getVm().getStaticData()); getCompensationContext().snapshotNewEntity(getVm().getStaticData()); }
Source:
<code>public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); <START> for (int i = start; i < start + length; i++) { <END> blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }</code><technical_language>[0..length)</technical_language>

Target:
public Block[] getSequenceBlocks(int start, int length) { BlockBuilder blockBuilder = UNKNOWN.createBlockBuilder(new BlockBuilderStatus(), length); for (int i = 0; i < length; i++) { blockBuilder.appendNull(); } return new Block[] {blockBuilder.build()}; }
Source:
<code>public static SetMultimap<ReviewerState, Account.Id> getReviewers( Iterable<PatchSetApproval> allApprovals) { PatchSetApproval first = null; SetMultimap<ReviewerState, Account.Id> reviewers = LinkedHashMultimap.create(); for (PatchSetApproval psa : allApprovals) { if (first == null) { first = psa; } else { checkArgument( first.getKey().getParentKey().getParentKey().equals( psa.getKey().getParentKey().getParentKey()), "multiple change IDs: %s, %s", first.getKey(), psa.getKey()); } Account.Id id = psa.getAccountId(); <START> if (psa.getValue() > 0) { <END> reviewers.put(ReviewerState.REVIEWER, id); reviewers.remove(ReviewerState.CC, id); } else if (!reviewers.containsEntry(ReviewerState.REVIEWER, id)) { reviewers.put(ReviewerState.CC, id); } } return Multimaps.unmodifiableSetMultimap(reviewers); }</code><technical_language>!= 0</technical_language>

Target:
public static SetMultimap<ReviewerState, Account.Id> getReviewers( Iterable<PatchSetApproval> allApprovals) { PatchSetApproval first = null; SetMultimap<ReviewerState, Account.Id> reviewers = LinkedHashMultimap.create(); for (PatchSetApproval psa : allApprovals) { if (first == null) { first = psa; } else { checkArgument( first.getKey().getParentKey().getParentKey().equals( psa.getKey().getParentKey().getParentKey()), "multiple change IDs: %s, %s", first.getKey(), psa.getKey()); } Account.Id id = psa.getAccountId(); if (psa.getValue() != 0) { reviewers.put(ReviewerState.REVIEWER, id); reviewers.remove(ReviewerState.CC, id); } else if (!reviewers.containsEntry(ReviewerState.REVIEWER, id)) { reviewers.put(ReviewerState.CC, id); } } return Multimaps.unmodifiableSetMultimap(reviewers); }
Source:
<code>public void addExistingModelElements(EObject eObject, EReference eReference) { final Iterator<EObject> allElements = ItemPropertyDescriptor .getReachableObjectsOfType(eObject, eReference.getEType()) .iterator(); Set<EObject> elements = new LinkedHashSet<EObject>(); while (allElements.hasNext()) { elements.add(allElements.next()); } elements = new HashSet<EObject>(eobjectStrategy.collectExistingObjects(eObject, eReference, elements)); ECPControlHelper.removeExistingReferences(eObject, eReference, elements); <START> final Set<EObject> addedElements = SelectModelElementWizardFactory <END> .openModelElementSelectionDialog(elements, eReference.isMany()); switch (addedElements.size()) { case 0: break; case 1: addReference.addElementToReference(eObject, eReference, addedElements.iterator().next()); break; default: addReference.addElementsToReference(eObject, eReference, addedElements); break; } }</code><technical_language>IMHO ReferenceService open UI dialogs this is inflexible. UI stuff part of strategies itself. Otherwise, end situation again: extend/overwrite default reference customize it</technical_language>

Target:
public void addExistingModelElements(EObject eObject, EReference eReference) { final Iterator<EObject> allElements = ItemPropertyDescriptor .getReachableObjectsOfType(eObject, eReference.getEType()) .iterator(); Set<EObject> elements = new LinkedHashSet<EObject>(); while (allElements.hasNext()) { elements.add(allElements.next()); } elements = new HashSet<EObject>(eobjectStrategy.collectExistingObjects(eObject, eReference, elements)); ECPControlHelper.removeExistingReferences(eObject, eReference, elements); final Set<EObject> addedElements = SelectModelElementWizardFactory .openModelElementSelectionDialog(elements, eReference.isMany()); switch (addedElements.size()) { case 0: break; case 1: addReference.addElementsToReference(eObject, eReference, singleton(addedElements.iterator().next())); break; default: addReference.addElementsToReference(eObject, eReference, addedElements); break; } }
Source:
<code>public static void init() throws Exception { Main.LOCAL.main(args); NetworkAccess toPki = buildApi(args); Multihash pkiNodeId = toPki.dhtClient.id().get(); PublicKeyHash peergosId = PublicKeyHash.fromString(args.getArg("peergos.identity.hash")); nodes.add(toPki); int bootstrapSwarmPort = args.getInt("ipfs-config-swarm-port"); for (int i = 0; i < 2; i++) { int ipfsApiPort = 9000 + random.nextInt(8000); int ipfsGatewayPort = 9000 + random.nextInt(8000); int ipfsSwarmPort = 9000 + random.nextInt(8000); int peergosPort = 9000 + random.nextInt(8000); Args normalNode = UserTests.buildArgs() .with("useIPFS", "true") .with("port", "" + peergosPort) .with("pki-node-id", pkiNodeId.toBase58()) .with("peergos.identity.hash", peergosId.toString()) .with("ipfs-config-api-port", "" + ipfsApiPort) .with("ipfs-config-gateway-port", "" + ipfsGatewayPort) .with("ipfs-config-swarm-port", "" + ipfsSwarmPort) .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, "" + Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId)) .with("proxy-target", Main.getLocalMultiAddress(peergosPort).toString()) .with("ipfs-api-address", Main.getLocalMultiAddress(ipfsApiPort).toString()) .with("mutable-pointers-file", ":memory:") .with("social-sql-file", ":memory:"); Main.PEERGOS.main(normalNode); <START> Thread.sleep(10_000); <END> IPFS ipfs = new IPFS(Main.getLocalMultiAddress(ipfsApiPort)); ipfs.swarm.connect(Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId).toString()); nodes.add(buildApi(normalNode)); } }</code><technical_language>sleep() call</technical_language>

Target:
public static void init() throws Exception { Main.PKI.main(args); NetworkAccess toPki = buildApi(args); Multihash pkiNodeId = toPki.dhtClient.id().get(); PublicKeyHash peergosId = PublicKeyHash.fromString(args.getArg("peergos.identity.hash")); nodes.add(toPki); int bootstrapSwarmPort = args.getInt("ipfs-config-swarm-port"); for (int i = 0; i < 2; i++) { int ipfsApiPort = 9000 + random.nextInt(8000); int ipfsGatewayPort = 9000 + random.nextInt(8000); int ipfsSwarmPort = 9000 + random.nextInt(8000); int peergosPort = 9000 + random.nextInt(8000); Args normalNode = UserTests.buildArgs() .with("useIPFS", "true") .with("port", "" + peergosPort) .with("pki-node-id", pkiNodeId.toBase58()) .with("peergos.identity.hash", peergosId.toString()) .with("ipfs-config-api-port", "" + ipfsApiPort) .with("ipfs-config-gateway-port", "" + ipfsGatewayPort) .with("ipfs-config-swarm-port", "" + ipfsSwarmPort) .with(IpfsWrapper.IPFS_BOOTSTRAP_NODES, "" + Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId)) .with("proxy-target", Main.getLocalMultiAddress(peergosPort).toString()) .with("ipfs-api-address", Main.getLocalMultiAddress(ipfsApiPort).toString()) .with("mutable-pointers-file", ":memory:") .with("social-sql-file", ":memory:"); Main.PEERGOS.main(normalNode); IPFS ipfs = new IPFS(Main.getLocalMultiAddress(ipfsApiPort)); ipfs.swarm.connect(Main.getLocalBootstrapAddress(bootstrapSwarmPort, pkiNodeId).toString()); nodes.add(buildApi(normalNode)); } }
Source:
<code>public void argumentsInScript() throws Exception { File xmlFile = tmpFolder.newFile(); TaskFlowJob job = new TaskFlowJob(); job.setName("simpleJob"); String params[] = { "param1", "param2" }; SimpleScript script = new SimpleScript("\nprint('arguments[0]='+arguments[0])\n", "javascript", params); ScriptTask task = new ScriptTask(); task.setName("testTask"); task.setScript(new TaskScript(script)); job.addTask(task); new Job2XMLTransformer().job2xmlFile(job, xmlFile); TaskFlowJob recreatedJob = (TaskFlowJob) (JobFactory.getFactory().createJob(xmlFile.getAbsolutePath())); <START> assertNotNull(((ScriptTask) recreatedJob.getTask("testTask")).getScript()); <END> }</code><technical_language>need test parameters</technical_language>

Target:
public void argumentsInScript() throws Exception { File xmlFile = tmpFolder.newFile(); TaskFlowJob job = new TaskFlowJob(); job.setName("simpleJob"); String params[] = { "param1", "param2" }; SimpleScript script = new SimpleScript("\nprint('arguments[0]='+arguments[0])\n", "javascript", params); ScriptTask task = new ScriptTask(); task.setName("testTask"); task.setScript(new TaskScript(script)); job.addTask(task); new Job2XMLTransformer().job2xmlFile(job, xmlFile); TaskFlowJob recreatedJob = (TaskFlowJob) (JobFactory.getFactory().createJob(xmlFile.getAbsolutePath())); Assert.assertEquals("param1", ((ScriptTask) recreatedJob.getTask("testTask")).getScript().getParameters()[0].toString()); Assert.assertEquals("param2", ((ScriptTask) recreatedJob.getTask("testTask")).getScript().getParameters()[1].toString()); }
Source:
<code>public int bulkInsert(List<Record> records) throws NullCursorException { if (records.isEmpty()) { Logger.debug(LOG_TAG, "No records to insert, returning."); } int size = records.size(); ContentValues[] cvs = new ContentValues[size]; int index = 0; for (Record record : records) { <START> cvs[index] = getContentValues(record); <END> index += 1; } int inserted = context.getContentResolver().bulkInsert(getUri(), cvs); if (inserted == size) { Logger.debug(LOG_TAG, "Inserted " + inserted + " records, as expected."); } else { Logger.debug(LOG_TAG, "Inserted " + inserted + " records but expected " + size + " records."); } return inserted; }</code><technical_language>Note getContentValues throw a runtime exception, for bookmarks want handle that</technical_language>

Target:
public int bulkInsert(List<Record> records) throws NullCursorException { if (records.isEmpty()) { Logger.debug(LOG_TAG, "No records to insert, returning."); } int size = records.size(); ContentValues[] cvs = new ContentValues[size]; int index = 0; for (Record record : records) { try { cvs[index] = getContentValues(record); index += 1; } catch (Exception e) { Logger.warn(LOG_TAG, "Got exception in getContentValues for record with guid " + record.guid, e); } } if (index != size) { size = index; ContentValues[] temp = new ContentValues[size]; System.arraycopy(cvs, 0, temp, 0, size); } int inserted = context.getContentResolver().bulkInsert(getUri(), cvs); if (inserted == size) { Logger.debug(LOG_TAG, "Inserted " + inserted + " records, as expected."); } else { Logger.debug(LOG_TAG, "Inserted " + inserted + " records but expected " + size + " records."); } return inserted; }
Source:
<code>private void impl$onSet(NBTTagCompound compound, CallbackInfo callbackInfo) { if (this.stackTagCompound != compound) { this.manipulators.clear(); } <START> if (shadow$hasTagCompound() && shadow$getTagCompound().hasKey(Constants.Sponge.SPONGE_DATA, Constants.NBT.TAG_COMPOUND)) { <END> DataUtil.readCustomData(shadow$getTagCompound().getCompoundTag(Constants.Sponge.SPONGE_DATA), ((org.spongepowered.api.item.inventory.ItemStack) this)); } }</code><technical_language>suggestion if (this.shadow$hasTagCompound() && this.shadow$getTagCompound().hasKey(Constants.Sponge.SPONGE_DATA, Constants.NBT.TAG_COMPOUND)) {</technical_language>

Target:
private void impl$onSet(NBTTagCompound compound, CallbackInfo callbackInfo) { if (this.stackTagCompound != compound) { this.manipulators.clear(); } if (this.shadow$hasTagCompound() && this.shadow$getTagCompound().hasKey(Constants.Sponge.SPONGE_DATA, Constants.NBT.TAG_COMPOUND)) { DataUtil.readCustomData(this.shadow$getTagCompound().getCompoundTag(Constants.Sponge.SPONGE_DATA), ((org.spongepowered.api.item.inventory.ItemStack) this)); } }
Source:
<code><START> public Boolean hasCommandSpy() <END> { return commandSpy; }</code><technical_language>commandSpy need getters/setters. lombok for that</technical_language>

Target:
public boolean hasCommandSpy() { return commandSpy; }
Source:
<code>private boolean isChanged(List<String> ol, List<String> nl) { if (ol.size() != nl.size()) return true; <START> for (int i = 0; i < ol.size(); i++) { <END> if (!ol.get(i).equals(nl.get(i))) return true; } return false; }</code><technical_language>style nit: curly braces single line blocks</technical_language>

Target:
private boolean isChanged(List<String> ol, List<String> nl) { if (ol.size() != nl.size()) return true; for (int i = 0; i < ol.size(); i++) if (!ol.get(i).equals(nl.get(i))) return true; return false; }
Source:
<code>public void builtin_symbol_in_super_class() { ClassSymbolImpl classASymbol = new ClassSymbolImpl("A", "mod1.A"); classASymbol.addSuperClass(new SymbolImpl("BaseException", "BaseException")); FileInput tree = parse( new SymbolTableBuilder("my_package", pythonFile("my_module.py"), Collections.singletonMap("mod1", Collections.singleton(classASymbol))), "from mod1 import A" ); Symbol importedASymbol = tree.globalVariables().iterator().next(); assertThat(importedASymbol.kind()).isEqualTo(Symbol.Kind.CLASS); ClassSymbol classA = (ClassSymbol) importedASymbol; assertThat(classA.hasUnresolvedTypeHierarchy()).isEqualTo(false); assertThat(classA.superClasses()).hasSize(1); <START> assertThat(classA.superClasses().get(0).kind()).isEqualTo(Symbol.Kind.OTHER); <END> }</code><technical_language>I feeling 2 contradict other: * a superclass is a class symbol * hasUnresolvedTypeHierarchy() returning false</technical_language>

Target:
public void builtin_symbol_in_super_class() { ClassSymbolImpl classASymbol = new ClassSymbolImpl("A", "mod1.A"); classASymbol.addSuperClass(new SymbolImpl("BaseException", "BaseException")); FileInput tree = parse( new SymbolTableBuilder("my_package", pythonFile("my_module.py"), Collections.singletonMap("mod1", Collections.singleton(classASymbol))), "from mod1 import A" ); Symbol importedASymbol = tree.globalVariables().iterator().next(); assertThat(importedASymbol.kind()).isEqualTo(Symbol.Kind.CLASS); ClassSymbol classA = (ClassSymbol) importedASymbol; assertThat(classA.hasUnresolvedTypeHierarchy()).isEqualTo(true); assertThat(classA.superClasses()).hasSize(1); assertThat(classA.superClasses().get(0).kind()).isEqualTo(Symbol.Kind.OTHER); }