auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public boolean equals(Object o) { <START> if (this == o) return true; <END> if (o == null || getClass() != o.getClass()) return false; LocalRepository that = (LocalRepository) o; return repositoryDirectory != null ? repositoryDirectory.equals(that.repositoryDirectory) : that.repositoryDirectory == null; }</code><technical_language>Sam remark</technical_language>

Target:
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } LocalRepository that = (LocalRepository) o; EqualsBuilder builder = new EqualsBuilder(); builder.append(repositoryDirectory, that.repositoryDirectory); return builder.isEquals(); }
Source:
<code>public GenericRowSorter(List<String> sortOrder, Schema schema) { int sortOrderSize = sortOrder.size(); Comparator[] comparators = new Comparator[sortOrderSize]; for (int i = 0; i < sortOrderSize; i++) { String column = sortOrder.get(i); FieldSpec fieldSpec = schema.getFieldSpecFor(column); Preconditions.checkState(fieldSpec.isSingleValueField(), "Cannot use multi value column: %s for sorting", column); <START> comparators[i] = getComparator(fieldSpec.getDataType()); <END> } _genericRowComparator = (o1, o2) -> { for (int i = 0; i < comparators.length; i++) { String column = sortOrder.get(i); int result = comparators[i].compare(o1.getValue(column), o2.getValue(column)); if (result != 0) { return result; } } return 0; }; }</code><technical_language>experience, storing dataType do per-value switch is faster storing Comparator</technical_language>

Target:
public GenericRowSorter(List<String> sortOrder, Schema schema) { int sortOrderSize = sortOrder.size(); FieldSpec.DataType[] dataTypes = new FieldSpec.DataType[sortOrderSize]; for (int i = 0; i < sortOrderSize; i++) { String column = sortOrder.get(i); FieldSpec fieldSpec = schema.getFieldSpecFor(column); Preconditions.checkState(fieldSpec != null, "Column in sort order: %s does not exist in schema", column); Preconditions.checkState(fieldSpec.isSingleValueField(), "Cannot use multi value column: %s for sorting", column); dataTypes[i] = fieldSpec.getDataType(); } _genericRowComparator = (o1, o2) -> { for (int i = 0; i < sortOrderSize; i++) { String column = sortOrder.get(i); FieldSpec.DataType dataType = dataTypes[i]; Object value1 = o1.getValue(column); Object value2 = o2.getValue(column); int result; switch (dataType) { case INT: result = Integer.compare((int) value1, (int) value2); break; case LONG: result = Long.compare((long) value1, (long) value2); break; case FLOAT: result = Float.compare((float) value1, (float) value2); break; case DOUBLE: result = Double.compare((double) value1, (double) value2); break; case STRING: result = ((String) value1).compareTo((String) value2); break; case BYTES: result = ByteArray.compare((byte[]) value1, (byte[]) value2); break; default: throw new IllegalStateException("Cannot sort on column with dataType " + dataType); } if (result != 0) { return result; } } return 0; }; }
Source:
<code>public AsyncTaskParameterSource(DbEngineDialect dialect,async_tasks task) { <START> super(dialect); <END> addValue("action_type", task.getaction_type()); addValue("result", task.getresult()); addValue("status", task.getstatus()); addValue("task_id", task.gettask_id()); task.getaction_parameters(); addValue("action_parameters", serializeParameters(task.getaction_parameters())); addValue("action_params_class",task.getaction_parameters().getClass().getName()); }</code><technical_language>is a repetition parameters field names, is worth extracting constants</technical_language>

Target:
public AsyncTaskParameterSource(DbEngineDialect dialect,async_tasks task) { super(dialect); addValue("action_type", task.getaction_type()); addValue("result", task.getresult()); addValue("status", task.getstatus()); addValue("task_id", task.gettask_id()); addValue("action_parameters", serializeParameters(task.getaction_parameters())); addValue("action_params_class",task.getaction_parameters().getClass().getName()); }
Source:
<code>public static <T> boolean put(String key, T value) { if (key == null) { throw new NullPointerException("Key cannot be null"); } if (value == null) { return remove(key); } if (!isHawkInitialised()) { <START> return false; <END> } String encodedText = zip(value); return encodedText != null && hawkBuilder.getStorage().put(key, encodedText); }</code><technical_language>Please exception. status used. If status "init_started", put operation later. I suggest a status "init_started". do think</technical_language>

Target:
public static <T> boolean put(String key, T value) { if (key == null) { throw new NullPointerException("Key cannot be null"); } Utils.validateBuild(); if (value == null) { return remove(key); } String encodedText = zip(value); return encodedText != null && internal.getStorage().put(key, encodedText); }
Source:
<code>public GHRef createRef(String name, String sha) throws IOException { return root.retrieve() <START> .method("POST") <END> .with("ref", name) .with("sha", sha) .method("POST") .withUrlPath(getApiTailUrl("git/refs")) .to(GHRef.class) .wrap(root); }</code><technical_language>redundant method("POST")</technical_language>

Target:
public GHRef createRef(String name, String sha) throws IOException { return root.createRequest() .method("POST") .with("ref", name) .with("sha", sha) .withUrlPath(getApiTailUrl("git/refs")) .fetch(GHRef.class) .wrap(root); }
Source:
<code>public org.eclipse.gef.commands.Command getGraphicalCommand(EditingDomain domain, GraphicalEditPart targetEditPart, PapyrusClipboard<Object> papyrusClipboard) { org.eclipse.gef.commands.CompoundCommand compoundCommand = new org.eclipse.gef.commands.CompoundCommand("Copy all stereotypes"); for(Iterator<EObject> iterator = papyrusClipboard.getTarget().iterator(); iterator.hasNext();) { EObject eObject = iterator.next(); if(eObject instanceof View) { View view = (View)eObject; String type = view.getType(); <START> if ("AppliedStereotypeCompartment".equals(type)){ END> org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand deleteCommand = new org.eclipse.gmf.runtime.diagram.core.commands.DeleteCommand((TransactionalEditingDomain)domain,view); GMFtoGEFCommandWrapper gmFtoGEFCommandWrapper = new GMFtoGEFCommandWrapper(deleteCommand); compoundCommand.add(gmFtoGEFCommandWrapper); } } } if (targetEditPart != null){ Object model = targetEditPart.getModel(); if (model instanceof View){ View view = (View)model; EObject targetOwner = view.getElement(); org.eclipse.emf.common.command.Command semanticCommand = this.getSemanticCommand(domain, targetOwner, papyrusClipboard); if (semanticCommand != null){ EMFtoGEFCommandWrapper emFtoGEFCommandWrapper = new EMFtoGEFCommandWrapper(semanticCommand); compoundCommand.add(emFtoGEFCommandWrapper); } } } return compoundCommand; }</code><technical_language>Sorry, I ask ... fixing FIXME</technical_language>

Target:
public org.eclipse.gef.commands.Command getGraphicalCommand(EditingDomain domain, GraphicalEditPart targetEditPart, PapyrusClipboard<Object> papyrusClipboard) { org.eclipse.gef.commands.CompoundCommand compoundCommand = new org.eclipse.gef.commands.CompoundCommand("Copy all stereotypes"); if (targetEditPart != null){ Object model = targetEditPart.getModel(); if (model instanceof View){ View view = (View)model; EObject targetOwner = view.getElement(); org.eclipse.emf.common.command.Command semanticCommand = this.getSemanticCommand(domain, targetOwner, papyrusClipboard); if (semanticCommand != null){ compoundCommand.add(EMFtoGEFCommandWrapper.wrap(semanticCommand)); } } } for(Iterator<EObject> iterator = papyrusClipboard.getTarget().iterator(); iterator.hasNext();) { EObject eObject = iterator.next(); if(eObject instanceof BasicCompartment) { BasicCompartment basicCompartment = (BasicCompartment) eObject; RestoreStereotypeCompartmentCommand refreshStereotypeCompartmentCommand = new RestoreStereotypeCompartmentCommand((TransactionalEditingDomain)domain,basicCompartment); Command wrap = EMFtoGEFCommandWrapper.wrap(refreshStereotypeCompartmentCommand); compoundCommand.add(wrap); } } if(compoundCommand.getCommands().isEmpty()) { return null; } return compoundCommand; }
Source:
<code>public List<V> pull(final List<K> keys) { final List<K> nonLocalKeys = new ArrayList<>(); <START> final List<V> valueList = new ArrayList(); <END> for (final K key : keys) { if (!localParameters.containsKey(key)) { nonLocalKeys.add(key); } } if (!nonLocalKeys.isEmpty()) { final List<V> remoteValues = parameterWorker.pull(nonLocalKeys); int i = 0; for (final K key : nonLocalKeys) { localParameters.put(key, remoteValues.get(i++)); } } for (final K key : keys) { valueList.add(localParameters.get(key)); } return valueList; }</code><technical_language>ArrayList<>();</technical_language>

Target:
public List<V> pull(final List<K> keys) { final List<K> nonLocalKeys = new ArrayList<>(); final List<V> valueList = new ArrayList<>(); for (final K key : keys) { if (!localParameters.containsKey(key)) { nonLocalKeys.add(key); } } if (!nonLocalKeys.isEmpty()) { final List<V> remoteValues = parameterWorker.pull(nonLocalKeys); int i = 0; for (final K key : nonLocalKeys) { localParameters.put(key, remoteValues.get(i++)); } } for (final K key : keys) { valueList.add(localParameters.get(key)); } return valueList; }
Source:
<code>public void setup() { kvs = new InMemoryKeyValueService(true); TimestampService tsService = new InMemoryTimestampService(); LockClient lockClient = LockClient.of("sweep client"); lockService = LockServiceImpl.create(LockServerOptions.builder().isStandaloneServer(false).build()); TransactionService txService = TransactionServices.createTransactionService(kvs); Supplier<AtlasDbConstraintCheckingMode> constraints = Suppliers.ofInstance( AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING); ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); SweepStrategyManager ssm = SweepStrategyManagers.createDefault(kvs); Cleaner cleaner = new NoOpCleaner(); SerializableTransactionManager transactionManager = new SerializableTransactionManager( <START> kvs, tsService, lockClient, lockService, txService, constraints, cdm, ssm, cleaner, false, 8, 2); <END> txManager = transactionManager; }</code><technical_language>of defaults</technical_language>

Target:
public void setup() { kvs = new InMemoryKeyValueService(true); TimestampService tsService = new InMemoryTimestampService(); LockClient lockClient = LockClient.of("sweep client"); lockService = LockServiceImpl.create(LockServerOptions.builder().isStandaloneServer(false).build()); TransactionService txService = TransactionServices.createTransactionService(kvs); Supplier<AtlasDbConstraintCheckingMode> constraints = Suppliers.ofInstance( AtlasDbConstraintCheckingMode.NO_CONSTRAINT_CHECKING); ConflictDetectionManager cdm = ConflictDetectionManagers.createWithoutWarmingCache(kvs); SweepStrategyManager ssm = SweepStrategyManagers.createDefault(kvs); Cleaner cleaner = new NoOpCleaner(); SerializableTransactionManager transactionManager = new SerializableTransactionManager( kvs, tsService, lockClient, lockService, txService, constraints, cdm, ssm, cleaner, false, AbstractTransactionTest.GET_RANGES_THREAD_POOL_SIZE, AbstractTransactionTest.DEFAULT_GET_RANGES_CONCURRENCY); txManager = transactionManager; }
Source:
<code>public void testRenderTopItemIndex_afterAllItems() throws IOException { new TreeItem( tree, SWT.NONE ); TreeItem item = new TreeItem( tree, SWT.NONE ); TreeColumn column = new TreeColumn( tree, SWT.NONE ); tree.setTopItem( item ); getLCA( display ).render( display ); TestMessage message = Fixture.getProtocolMessage(); <START> CreateOperation operation1 = message.findCreateOperation( item ); <END> CreateOperation operation2 = message.findCreateOperation( column ); SetOperation operation3 = message.findSetOperation( tree, "topItemIndex" ); assertNotNull( operation1 ); assertNotNull( operation2 ); assertNotNull( operation3 ); List<Operation> operations = message.getOperations(); assertTrue( findIndex( operations, operation1 ) < findIndex( operations, operation3 ) ); assertTrue( findIndex( operations, operation2 ) < findIndex( operations, operation3 ) ); }</code><technical_language>this method replaced operations.indexOf(operation)</technical_language>

Target:
public void testRenderTopItemIndex_afterAllItems() throws IOException { new TreeItem( tree, SWT.NONE ); TreeItem item = new TreeItem( tree, SWT.NONE ); TreeColumn column = new TreeColumn( tree, SWT.NONE ); tree.setTopItem( item ); getLCA( display ).render( display ); TestMessage message = Fixture.getProtocolMessage(); CreateOperation operation1 = message.findCreateOperation( item ); CreateOperation operation2 = message.findCreateOperation( column ); SetOperation operation3 = message.findSetOperation( tree, "topItemIndex" ); assertNotNull( operation1 ); assertNotNull( operation2 ); assertNotNull( operation3 ); List<Operation> operations = message.getOperations(); assertTrue( operations.indexOf( operation1 ) < operations.indexOf( operation3 ) ); assertTrue( operations.indexOf( operation2 ) < operations.indexOf( operation3 ) ); }
Source:
<code>public void addStateTo(StateDumpCollector dump) { ClusterTierDump.dump(dump, managerIdentifier, storeIdentifier, configuration); { Map<ClientDescriptor, ClusterTierClientState> clients = new HashMap<>(connectedClients); dump.addState("clientCount", String.valueOf(clients.size())); <START> List<Map> allClients = new ArrayList<>(); <END> for (Map.Entry<ClientDescriptor, ClusterTierClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("storeIdentifier", entry.getValue().getStoreIdentifier()); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); allClients.add(clientMap); } dump.addState("clients", allClients); } }</code><technical_language>size of list</technical_language>

Target:
public void addStateTo(StateDumpCollector dump) { ClusterTierDump.dump(dump, managerIdentifier, storeIdentifier, configuration); { Map<ClientDescriptor, ClusterTierClientState> clients = new HashMap<>(connectedClients); List<Map> allClients = new ArrayList<>(clients.size()); for (Map.Entry<ClientDescriptor, ClusterTierClientState> entry : clients.entrySet()) { Map<String,String> clientMap = new HashMap<>(4); clientMap.put("clientDescriptor", entry.getKey().toString()); clientMap.put("clientIdentifier", String.valueOf(entry.getValue().getClientIdentifier())); clientMap.put("storeIdentifier", entry.getValue().getStoreIdentifier()); clientMap.put("attached", String.valueOf(entry.getValue().isAttached())); allClients.add(clientMap); } dump.addState("clientCount", String.valueOf(allClients.size())); dump.addState("clients", allClients); } }
Source:
<code>private static boolean cannotBeCombined(CharSequence name) { <START> return CASE_SENSITIVE_HASHER.equals(SET_COOKIE, name); <END> }</code><technical_language>I SET_COOKIE.contentEqualsIgnoreCase(...)</technical_language>

Target:
private static boolean cannotBeCombined(CharSequence name) { return SET_COOKIE.contentEqualsIgnoreCase(name); }
Source:
<code>public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { String pathInfo = req.getPathInfo(); <START> if (pathInfo == null || pathInfo.equals("")) { <END> return false; } pathInfo = !pathInfo.endsWith("/") ? pathInfo + '/' : pathInfo; if (!pathInfo.equals(getExclusionPath())) { return false; } chain.doFilter(req, resp); return true; }</code><technical_language>StringUtils.isEmpty() (AFAIR) static import</technical_language>

Target:
public boolean process(HttpServletRequest req, HttpServletResponse resp, FilterChain chain) throws IOException, ServletException { String pathInfo = req.getPathInfo(); if (isEmpty(pathInfo)) { return false; } pathInfo = pathInfo.endsWith("/") ? pathInfo : pathInfo + '/'; if (!pathInfo.equals(getExclusionPath())) { return false; } chain.doFilter(req, resp); return true; }
Source:
<code>protected boolean checkReadOnly() throws OperationNotSupportedException { if (readOnly) { <START> if("true".equals(System.getProperty("jndiExceptionOnFailedWrite"))) { <END> throw new OperationNotSupportedException(); } return true; } return false; }</code><technical_language>SystemInstance.get().getProperty openejb prefix well, default fail</technical_language>

Target:
protected boolean checkReadOnly() throws OperationNotSupportedException { if (readOnly) { if("true".equals(SystemInstance.get().getProperty(JNDI_EXCEPTION_ON_FAILED_WRITE,"true"))) { throw new OperationNotSupportedException(); } return true; } return false; }
Source:
<code>protected Future<Boolean> reindexSinceAsync( final JcrWorkspace workspace, final long timestamp ) { ChangeJournal journal = runningState.journal(); assert journal != null; <START> Set<NodeKey> changedNodes = journal.changedNodesSince(timestamp); <END> if (changedNodes.isEmpty()) { return new ImmediateFuture<>(Boolean.FALSE); } return reindexSinceAsync(workspace.getSession().cache().getWorkspace(), getIndexWriter(), changedNodes); }</code><technical_language>.. here, too. :-)</technical_language>

Target:
protected Future<Boolean> reindexSinceAsync( final JcrWorkspace workspace, final long timestamp ) { ChangeJournal journal = runningState.journal(); assert journal != null; Iterator<NodeKey> changedNodes = journal.changedNodesSince(timestamp); if (!changedNodes.hasNext()) { return new ImmediateFuture<>(Boolean.FALSE); } return reindexSinceAsync(workspace.getSession().cache().getWorkspace(), getIndexWriter(), changedNodes); }
Source:
<code>public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { <START> if(tab == EsteemedInnovation.tab) { <END> for (Types type : Types.values()) { items.add(new ItemStack(this, 1, type.getMeta())); } } }</code><technical_language>Missing space if</technical_language>

Target:
public void getSubItems(CreativeTabs tab, NonNullList<ItemStack> items) { if (isInCreativeTab(tab)) { for (Types type : Types.values()) { items.add(new ItemStack(this, 1, type.getMeta())); } } }
Source:
<code>private void initUserSettings(final int userId) { getOnce(userId) <START> .toMaybe() <END> .filter(UserSettings::isNone) .subscribe(userSettings -> { put(new UserSettings(DEFAULT_REPOSITORY_ID)); }); }</code><technical_language>Is this needed? Removing work</technical_language>

Target:
private void initUserSettings(final int userId) { getOnce(userId) .filter(UserSettings::isNone) .subscribe(__ -> put(new UserSettings(DEFAULT_REPOSITORY_ID))); }
Source:
<code>public <T> T getService(long l, ServiceConfiguration<T> serviceConfiguration) { Class<T> serviceType = serviceConfiguration.getServiceType(); <START> return !serviceType.equals(DetailedServerStateImpl.class) ? null : serviceType.cast(detailedServerState); <END> }</code><technical_language>code be: rerturn serviceType != DetailedServerState.class ? mull : ... (implementation is hidden, interface needs in -api)</technical_language>

Target:
public <T> T getService(long l, ServiceConfiguration<T> serviceConfiguration) { Class<T> serviceType = serviceConfiguration.getServiceType(); return !serviceType.equals(DetailedServerState.class) ? null : serviceType.cast(detailedServerState); }
Source:
<code>private boolean hasMissingVm(PagedList<VirtualMachine> virtualMachines, Collection<String> privateInstanceIds) { Set<String> virtualMachineNames = virtualMachines .stream() .map(VirtualMachine::name) .collect(Collectors.toSet()); <START> boolean hasMissingVm = !virtualMachineNames.containsAll(privateInstanceIds); if (hasMissingVm) { LOGGER.info("Fetched VM id-s ({}) do not contain one of the following id-s: {}", virtualMachineNames, privateInstanceIds); } return !hasMissingVm; <END> }</code><technical_language>If possible, I get rid of double negation</technical_language>

Target:
private boolean hasMissingVm(PagedList<VirtualMachine> virtualMachines, Collection<String> privateInstanceIds) { Set<String> virtualMachineNames = virtualMachines .stream() .map(VirtualMachine::name) .collect(Collectors.toSet()); boolean hasMissingVm = !virtualMachineNames.containsAll(privateInstanceIds); if (hasMissingVm) { LOGGER.info("Fetched VM id-s ({}) do not contain one of the following id-s: {}", virtualMachineNames, privateInstanceIds); } return hasMissingVm; }
Source:
<code>public Map<String, String> parseParams(String envParams, boolean substitueFromConfig) { <START> if (org.apache.commons.lang3.StringUtils.isEmpty(envParams)) { <END> return Collections.EMPTY_MAP; } Map<String, String> extraEnvParamsMap = new HashMap<>(); Arrays.stream(envParams.split(",")) .forEach( pair1 -> { String[] pair = pair1.split("="); if (pair.length > 1) { String key, value; if (substitueFromConfig) { key = pair[1]; value = getProperty(pair[0], String.class); } else { key = pair[0]; value = pair[1]; } if (!org.apache.commons.lang3.StringUtils.isBlank(key) && !org.apache.commons.lang3.StringUtils.isBlank(value)) { extraEnvParamsMap.put(key, value); } } }); return extraEnvParamsMap; }</code><technical_language>Import org.apache.commons.lang3.StringUtils</technical_language>

Target:
public Map<String, String> parseParams(String envParams, boolean substitueFromConfig) { if (StringUtils.isEmpty(envParams)) { return Collections.EMPTY_MAP; } Map<String, String> extraEnvParamsMap = new HashMap<>(); Arrays.stream(envParams.split(",")) .forEach( pair1 -> { String[] pair = pair1.split("="); if (pair.length > 1) { String key, value; if (substitueFromConfig) { key = pair[1]; value = getProperty(pair[0], String.class); } else { key = pair[0]; value = pair[1]; } if (!StringUtils.isBlank(key) && !StringUtils.isBlank(value)) { extraEnvParamsMap.put(key, value); } } }); return extraEnvParamsMap; }
Source:
<code>public void init(Permission perm) { path = node.getName().replaceAll("%2F", "/"); initData(node); GetHistory.initAction(node, getGroup().getDb()); { NodeBuilder b = node.createChild("unsubscribe"); b.setSerializable(false); b.setDisplayName("Unsubscribe"); b.setAction(new Action(perm, new Handler<ActionResult>() { @Override public void handle(ActionResult event) { unsubscribe(); } })); b.build(); } if (!group.canWriteOnNewData()) { <START> ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); <END> long interval = group.getInterval(); ScheduledFuture<?> scheduledFuture = scheduler.scheduleAtFixedRate(writeValues, 0, interval, TimeUnit.MILLISECONDS); } }</code><technical_language>This shared</technical_language>

Target:
public void init(Permission perm) { path = node.getName().replaceAll("%2F", "/").replaceAll("%2E", "."); initData(node); GetHistory.initAction(node, getGroup().getDb()); { NodeBuilder b = node.createChild("unsubscribe"); b.setSerializable(false); b.setDisplayName("Unsubscribe"); b.setAction(new Action(perm, new Handler<ActionResult>() { @Override public void handle(ActionResult event) { unsubscribe(); } })); b.build(); } group.addWatch(this); }
Source:
<code><START> public static String toHex(byte[] bytes) { <END> StringBuilder buffer = new StringBuilder(); for (byte b : bytes) { buffer.append(String.format(Locale.getDefault(), "%02x", b)); } return buffer.toString(); }</code><technical_language>This private, I</technical_language>

Target:
private static String toHex(byte[] bytes) { StringBuilder buffer = new StringBuilder(); for (byte b : bytes) { buffer.append(String.format(Locale.getDefault(), "%02x", b)); } return buffer.toString(); }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { String profileName = (String) request.getAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) request.getAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { <START> String engineSessionId = UUID.randomUUID().toString(); <END> InitialContext context = new InitialContext(); try { VdcReturnValueBase returnValue = FiltersHelper.getBackend(context).login(new LoginUserParameters( profileName, authRecord, engineSessionId, loginAsAdmin ? VdcActionType.LoginAdminUser : VdcActionType.LoginUser) ); if (returnValue.getSucceeded()) { HttpSession session = req.getSession(true); session.setAttribute( FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, engineSessionId ); } } finally { context.close(); } } } doFilter = true; } catch (Exception ex) { log.error(String.format("Error in login to engine. Message is: %1$s", ex.getMessage())); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }</code><technical_language>move this try</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { boolean doFilter = false; try { HttpServletRequest req = (HttpServletRequest) request; if (!FiltersHelper.isAuthenticated(req)) { String profileName = (String) request.getAttribute(FiltersHelper.Constants.REQUEST_PROFILE_KEY); ExtMap authRecord = (ExtMap) request.getAttribute(FiltersHelper.Constants.REQUEST_AUTH_RECORD_KEY); if (authRecord != null) { InitialContext context = new InitialContext(); try { VdcLoginReturnValueBase returnValue = (VdcLoginReturnValueBase)FiltersHelper.getBackend(context).login(new LoginUserParameters( profileName, authRecord, loginAsAdmin ? VdcActionType.LoginAdminUser : VdcActionType.LoginUser) ); if (returnValue.getSucceeded()) { HttpSession session = req.getSession(true); session.setAttribute( FiltersHelper.Constants.HTTP_SESSION_ENGINE_SESSION_ID_KEY, returnValue.getSessionId() ); } } finally { context.close(); } } } doFilter = true; } catch (Exception ex) { log.error(String.format("Error in login to engine. Message is: %1$s", ex.getMessage())); ((HttpServletResponse) response).sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } if (doFilter) { chain.doFilter(request, response); } }
Source:
<code>private void updateGetAlignmentCommandAvailability() { getScanAlignmentCommand().setIsExecutionAllowed(false); if (getSelectedItems() == null || getSelectedItems().size() != 1) { return; } ArrayList<Disk> disks = getSelectedItems() != null ? Linq.<Disk> cast(getSelectedItems()) : new ArrayList<Disk>(); for (Disk disk : disks) { if (!isImageDiskOK(disk)) { return; } } final VM vm = getEntity(); <START> AsyncDataProvider.getDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { <END> @Override public void onSuccess(Object target, Object returnValue) { VmDiskListModel model = (VmDiskListModel) target; StoragePool dataCenter = (StoragePool) returnValue; Version minClusterVersion = vm.getVdsGroupCompatibilityVersion(); Version minDcVersion = dataCenter.getcompatibility_version(); AsyncDataProvider.isCommandCompatible(new AsyncQuery(model, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmDiskListModel model = (VmDiskListModel) target; model.getScanAlignmentCommand().setIsExecutionAllowed((Boolean) returnValue); } }), VdcActionType.GetDiskAlignment, minClusterVersion, minDcVersion); } }), vm.getStoragePoolId().getValue()); }</code><technical_language>getDataCenterById query called disk selection. Instead, call - VM selection (on setEntity method). fixed a separate patch, please forget :)</technical_language>

Target:
private void updateGetAlignmentCommandAvailability() { getScanAlignmentCommand().setIsExecutionAllowed(false); if (getSelectedItems() == null || getSelectedItems().size() != 1) { return; } ArrayList<Disk> disks = getSelectedItems() != null ? Linq.<Disk> cast(getSelectedItems()) : new ArrayList<Disk>(); for (Disk disk : disks) { if (!isImageDiskOK(disk)) { return; } } final VM vm = getEntity(); AsyncDataProvider.getDataCenterById(new AsyncQuery(this, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmDiskListModel model = (VmDiskListModel) target; StoragePool dataCenter = (StoragePool) returnValue; Version minClusterVersion = vm.getVdsGroupCompatibilityVersion(); Version minDcVersion = dataCenter.getcompatibility_version(); AsyncDataProvider.isCommandCompatible(new AsyncQuery(model, new INewAsyncCallback() { @Override public void onSuccess(Object target, Object returnValue) { VmDiskListModel model = (VmDiskListModel) target; model.getScanAlignmentCommand().setIsExecutionAllowed((Boolean) returnValue); } }), VdcActionType.GetDiskAlignment, minClusterVersion, minDcVersion); } }), vm.getStoragePoolId()); }
Source:
<code>protected ArviointiasteikkoYleissivistava meanGrade(Collection<ArviointiasteikkoYleissivistava> grades) { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.isNumeric(grade))) { int gradeSum = 0; int gradeCount = 0; for (ArviointiasteikkoYleissivistava grade : grades) { if (ArviointiasteikkoYleissivistava.isNumeric(grade)) { gradeSum += Integer.valueOf(grade.toString()); gradeCount++; } } if (gradeCount > 0) { return ArviointiasteikkoYleissivistava.get(String.valueOf(Math.round((double) gradeSum / gradeCount))); } else <START> return null; <END> } else { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.isLiteral(grade))) { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.GRADE_S == grade)) return ArviointiasteikkoYleissivistava.GRADE_S; else return ArviointiasteikkoYleissivistava.GRADE_H; } else return null; } }</code><technical_language>braces - especially important "else" clauses other</technical_language>

Target:
protected ArviointiasteikkoYleissivistava meanGrade(Collection<ArviointiasteikkoYleissivistava> grades) { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.isNumeric(grade))) { int gradeSum = 0; int gradeCount = 0; for (ArviointiasteikkoYleissivistava grade : grades) { if (ArviointiasteikkoYleissivistava.isNumeric(grade)) { gradeSum += Integer.valueOf(grade.toString()); gradeCount++; } } if (gradeCount > 0) { return ArviointiasteikkoYleissivistava.get(String.valueOf(Math.round((double) gradeSum / gradeCount))); } else { return null; } } else { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.isLiteral(grade))) { if (grades.stream().anyMatch(grade -> ArviointiasteikkoYleissivistava.GRADE_S == grade)) { return ArviointiasteikkoYleissivistava.GRADE_S; } else { return ArviointiasteikkoYleissivistava.GRADE_H; } } else { return null; } } }
Source:
<code>public void onSuccess() { if (!flag) { if (!projectNodes.isEmpty()) { try { doFrontEndWork(jTree, model, root, codePaneTinyEditorsInfoList, projectNodes); jTabbedPane.setSelectedIndex(1); } catch (RuntimeException rte) { jTabbedPane.setSelectedIndex(0); <START> showHelpInfo(rte.getMessage()); <END> } } else { showHelpInfo(String.format(QUERY_HELP_MESSAGE, importsInLines.toString().replaceAll(",", "<br/>"))); jTree.updateUI(); notification.expire(); } } else { showHelpInfo(httpErrorMsg); } }</code><technical_language>if this throws exception ? + showHelp do setSelectedIndex(0) in it. I for rte.printstacktrace only</technical_language>

Target:
public void onSuccess() { if (!isFailed) { if (!projectNodes.isEmpty()) { try { doFrontEndWork(jTree, model, root, codePaneTinyEditorsInfoList, projectNodes); jTabbedPane.setSelectedIndex(1); } catch (RuntimeException rte) { rte.printStackTrace(); } } else { showHelpInfo(String.format(QUERY_HELP_MESSAGE, importsInLines.toString().replaceAll(",", "<br/>"))); jTree.updateUI(); notification.expire(); } } else { showHelpInfo(httpErrorMsg); } }
Source:
<code>public void testMultipleClients() throws Exception { Injector injector = new Bootstrap( <START> (Module) binder -> { <END> httpClientBinder(binder).bindHttpClient("foo", FooClient.class); httpClientBinder(binder).bindHttpClient("bar", BarClient.class); }) .quiet() .strictConfig() .initialize(); HttpClient fooClient = injector.getInstance(Key.get(HttpClient.class, FooClient.class)); HttpClient barClient = injector.getInstance(Key.get(HttpClient.class, BarClient.class)); assertNotSame(fooClient, barClient); assertNotNull(injector.getExistingBinding(Key.get(JettyIoPoolManager.class, FooClient.class))); assertNotNull(injector.getExistingBinding(Key.get(JettyIoPoolManager.class, BarClient.class))); assertJettyIoPools(injector, FooClient.class); assertJettyIoPools(injector, BarClient.class); assertPoolsDestroyProperly(injector, FooClient.class, BarClient.class); }</code><technical_language>I casts needed. code worked I removed them</technical_language>

Target:
public void testMultipleClients() throws Exception { Injector injector = new Bootstrap( binder -> { httpClientBinder(binder).bindHttpClient("foo", FooClient.class); httpClientBinder(binder).bindHttpClient("bar", BarClient.class); }) .quiet() .strictConfig() .initialize(); HttpClient fooClient = injector.getInstance(Key.get(HttpClient.class, FooClient.class)); HttpClient barClient = injector.getInstance(Key.get(HttpClient.class, BarClient.class)); assertNotSame(fooClient, barClient); assertNotNull(injector.getExistingBinding(Key.get(JettyIoPoolManager.class, FooClient.class))); assertNotNull(injector.getExistingBinding(Key.get(JettyIoPoolManager.class, BarClient.class))); assertJettyIoPools(injector, FooClient.class); assertJettyIoPools(injector, BarClient.class); assertPoolsDestroyProperly(injector, FooClient.class, BarClient.class); }
Source:
<code><START> public void testCorrectGetQueryForming() { <END> String formedQuery = DUMMY_QUERY_FORMER.formQuery(QueryFormer.SupportedQuery.GET, "test", DUMMY_TABLE_REFERENCE); assertThat(formedQuery).isEqualTo(DUMMY_GET_QUERY); }</code><technical_language>this test implies testFormattedQuery testFullyQualifiedName imo</technical_language>

Target:
public void testCorrectGetQueryForming() { String formedQuery = DUMMY_QUERY_FORMER.formQuery(SupportedQuery.GET, "test", DUMMY_TABLE_REFERENCE); assertThat(formedQuery).isEqualTo(DUMMY_GET_QUERY); }
Source:
<code>public ValueType typeCheck(TypeContext ctx) { List<DeclType> dts = new LinkedList<DeclType>(); TypeContext thisCtx = ctx.extend(selfName, getExprType()); boolean isResource = false; for (Declaration d : decls_ExceptDelegate()) { DeclType dt = d.typeCheck(ctx, thisCtx); <START> if (d instanceof DefDeclaration && ((DefDeclaration)d).isResource()) { <END> isResource = true; } dts.add(dt); } ValueType type = getExprType(); if (hasDelegate) { ValueType delegateObjectType = ctx.lookupType(delegateDeclaration.getFieldName()); StructuralType delegateStructuralType = delegateObjectType.getStructuralType(thisCtx); for (DeclType declType : delegateStructuralType.getDeclTypes()) { if (!dts.stream().anyMatch(newDefDeclType-> newDefDeclType.isSubtypeOf(declType, thisCtx))) { dts.add(declType); } } } StructuralType requiredT = type.getStructuralType(ctx); StructuralType actualT = new StructuralType(selfName, dts); if (!actualT.isSubtypeOf(requiredT, ctx)) { ToolError.reportError(ErrorMessage.NOT_SUBTYPE, this, actualT.getSelfName(), requiredT.getSelfName());; } if (isResource && !requiredT.isResource()) { ToolError.reportError(ErrorMessage.MUST_BE_RESOURCE_TYPE, this, requiredT.getSelfName()); } return type; }</code><technical_language>Avoid instanceof. Instead, rename isResource capturesResource/containsResource element of Declaration, DefDeclaration. This is a nice solution making objects vars a resource type</technical_language>

Target:
public ValueType typeCheck(TypeContext ctx) { List<DeclType> dts = new LinkedList<DeclType>(); TypeContext thisCtx = ctx.extend(selfName, getExprType()); boolean isResource = false; for (Declaration d : decls_ExceptDelegate()) { DeclType dt = d.typeCheck(ctx, thisCtx); dts.add(dt); if (d.containsResource()) { isResource = true; } } ValueType type = getExprType(); if (hasDelegate) { ValueType delegateObjectType = ctx.lookupType(delegateDeclaration.getFieldName()); StructuralType delegateStructuralType = delegateObjectType.getStructuralType(thisCtx); for (DeclType declType : delegateStructuralType.getDeclTypes()) { if (!dts.stream().anyMatch(newDefDeclType-> newDefDeclType.isSubtypeOf(declType, thisCtx))) { dts.add(declType); } } } StructuralType requiredT = type.getStructuralType(ctx); StructuralType actualT = new StructuralType(selfName, dts); if (!actualT.isSubtypeOf(requiredT, ctx)) { ToolError.reportError(ErrorMessage.NOT_SUBTYPE, this, actualT.getSelfName(), requiredT.getSelfName());; } if (isResource && !requiredT.isResource(GenContext.empty())) { ToolError.reportError(ErrorMessage.MUST_BE_RESOURCE_TYPE, this, requiredT.getSelfName()); } return type; }
Source:
<code>public ChannelFuture writeToChannel(RedisResponse response) { <START> if (response == null) { <END> return null; } return channel.writeAndFlush(response.encode(byteBufAllocator), channel.newPromise()) .addListener((ChannelFutureListener) f -> { response.afterWrite(); logResponse(response); }); }</code><technical_language>this null check is longer needed</technical_language>

Target:
public ChannelFuture writeToChannel(RedisResponse response) { return channel.writeAndFlush(response.encode(byteBufAllocator), channel.newPromise()) .addListener((ChannelFutureListener) f -> { response.afterWrite(); logResponse(response, channel.remoteAddress().toString(), f.cause()); }); }
Source:
<code>public Object parse(ElementInstance instance, Node node, Object value) throws Exception { Expression[] operands = OGCUtils.spatial(node, filterFactory, geometryFactory); double distance = ((Double) node.getChildValue(Double.class)).doubleValue(); <START> String units = node.getChild("Distance").getAttributeValue("units").toString(); <END> return filterFactory.beyond(operands[0], operands[1], distance, units); }</code><technical_language>is behaviour of getAttributeValue() is attribute? return null, empty string? Wondering if this is npe safe</technical_language>

Target:
public Object parse(ElementInstance instance, Node node, Object value) throws Exception { Expression[] operands = OGCUtils.spatial(node, filterFactory, geometryFactory); double distance = ((Double) node.getChildValue(Double.class)).doubleValue(); Object units = node.getChild("Distance").getAttributeValue("units"); return filterFactory.beyond(operands[0], operands[1], distance, units==null? null : units.toString()); }
Source:
<code>void notifyError(Throwable cause) { <START> notifyError(new ErrorResponse(cause, op.getCallId(), op.isUrgent())); <END> }</code><technical_language>This redundant. notifyError(ErrorResponse response) care ErrorResponse object, unwraps cause. I existing version is better, need wrap/unwrap</technical_language>

Target:
void notifyError(Throwable cause) { assert cause != null; switch (onException(cause)) { case RETRY_INVOCATION: if (invokeCount < tryCount) { handleRetry(cause); break; } case THROW_EXCEPTION: completeExceptionally(cause); break; default: throw new IllegalStateException("Unhandled ExceptionAction"); } }
Source:
<code><START> public void addBadge(Object projectIdOrPath, Badge badge) throws GitLabApiException { <END> Form formData = new Form(); formData.param("id", String.valueOf(getProjectIdOrPath(projectIdOrPath))); formData.param("link_url", badge.getLink_url()); formData.param("image_url", badge.getImage_url()); post(Response.Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "badges"); }</code><technical_language>This method is defined causing a compile failure</technical_language>

Target:
public void addBadge(Object projectIdOrPath, Badge badge) throws GitLabApiException { Form formData = new Form(); formData.param("id", String.valueOf(getProjectIdOrPath(projectIdOrPath))); formData.param("link_url", badge.getLinkUrl()); formData.param("image_url", badge.getImageUrl()); post(Response.Status.OK, formData, "projects", getProjectIdOrPath(projectIdOrPath), "badges"); }
Source:
<code>private static boolean hasUnbracedStatements(DetailAST ast) { final DetailAST nextSibling = ast.getNextSibling(); final DetailAST parent = ast.getParent(); boolean result = false; if (parent.getType() == TokenTypes.SWITCH_RULE) { <START> final DetailAST lastSibling = getLastSibling(ast); <END> result = lastSibling.getType() != TokenTypes.SLIST; } else if (nextSibling != null && nextSibling.getType() == TokenTypes.SLIST && nextSibling.getFirstChild().getType() != TokenTypes.SLIST) { result = true; } return result; }</code><technical_language>getLastSibling == parent.getLastChild(), reason for new method here</technical_language>

Target:
private static boolean hasUnbracedStatements(DetailAST ast) { final DetailAST nextSibling = ast.getNextSibling(); boolean result = false; if (isInSwitchRule(ast)) { final DetailAST parent = ast.getParent(); result = parent.getLastChild().getType() != TokenTypes.SLIST; } else if (nextSibling != null && nextSibling.getType() == TokenTypes.SLIST && nextSibling.getFirstChild().getType() != TokenTypes.SLIST) { result = true; } return result; }
Source:
<code><START> public TerminalInfoView() { <END> addToList(this); }</code><technical_language>call super() here</technical_language>

Target:
public TerminalInfoView() { super(); addToList(this); }
Source:
<code>public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RemoveImageCommand<RemoveImageParameters> cmd = CommandCoordinatorUtil.retrieveCommand(cmdId); if (asyncRetVal == null) { DiskImage diskImage = cmd.getDiskImage(); Guid storagePoolId = diskImage.getStoragePoolId() != null ? diskImage.getStoragePoolId() : Guid.Empty; Guid storageDomainId = Guid.isNullOrEmpty(cmd.getParameters().getStorageDomainId()) && cmd.getDiskImage() != null ? diskImage.getStorageIds().get(0) : cmd.getParameters().getStorageDomainId(); asyncRetVal = ResourceManager.getInstance().runAsyncVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, diskImage.getId(), diskImage.getImageId())); } if (asyncRetVal != null && asyncRetVal.isRequestCompleted()) { Object retVal = asyncRetVal.getReturnValue(); if (retVal != null) { DiskImage di = (DiskImage) retVal; <START> log.info("DiskImage retrieved " + di.getId()); <END> log.info("DiskImage In command " + cmd.getDiskImage().getId()); } if (!asyncRetVal.getSucceeded()) { cmd.setCommandStatus(CommandStatus.SUCCEEDED); } else { asyncRetVal = null; } } }</code><technical_language>please supported notation: log.info("DiskImage retrieved '{}'", di.getId());</technical_language>

Target:
public void doPolling(Guid cmdId, List<Guid> childCmdIds) { RemoveImageCommand<RemoveImageParameters> cmd = CommandCoordinatorUtil.retrieveCommand(cmdId); if (asyncRetVal == null) { DiskImage diskImage = cmd.getDiskImage(); Guid storagePoolId = diskImage.getStoragePoolId() != null ? diskImage.getStoragePoolId() : Guid.Empty; Guid storageDomainId = Guid.isNullOrEmpty(cmd.getParameters().getStorageDomainId()) && cmd.getDiskImage() != null ? diskImage.getStorageIds().get(0) : cmd.getParameters().getStorageDomainId(); asyncRetVal = ResourceManager.getInstance().runAsyncVdsCommand(VDSCommandType.GetImageInfo, new GetImageInfoVDSCommandParameters(storagePoolId, storageDomainId, diskImage.getId(), diskImage.getImageId())); } if (asyncRetVal != null && asyncRetVal.isRequestCompleted()) { asyncRetVal.getReturnValue(); cmd.setCommandStatus(asyncRetVal.getSucceeded() ? CommandStatus.SUCCEEDED : CommandStatus.FAILED); } }
Source:
<code>public Map<String, Set<DatastreamTask>> assign(List<DatastreamGroup> datastreams, List<String> instances, Map<String, Set<DatastreamTask>> currentAssignment) { LOG.info("Trying to assign datastreams to instances and the current assignment is {}", datastreams, instances, currentAssignment); Map<String, Set<DatastreamTask>> newAssignment = new HashMap<>(); for (String instance : instances) { newAssignment.put(instance, new HashSet<>()); <START> currentAssignment.putIfAbsent(instance, new HashSet<>()); <END> } Map<String, Set<DatastreamTask>> currentAssignmentCopy = new HashMap<>(currentAssignment.size()); currentAssignment.forEach((k, v) -> currentAssignmentCopy.put(k, new HashSet<>(v))); int instancePos = 0; for (DatastreamGroup dg : datastreams) { int numTasks = getNumTasks(dg, instances.size()); for (int taskPos = 0; taskPos < numTasks; taskPos++) { String instance = instances.get(instancePos); DatastreamTask foundDatastreamTask = currentAssignmentCopy.get(instance) .stream() .filter(x -> x.getTaskPrefix().equals(dg.getTaskPrefix())) .findFirst() .orElse(new DatastreamTaskImpl(dg.getDatastreams())); currentAssignmentCopy.get(instance).remove(foundDatastreamTask); newAssignment.get(instance).add(foundDatastreamTask); instancePos = (instancePos + 1) % instances.size(); } } LOG.info("New assignment is {}", newAssignment); return newAssignment; }</code><technical_language>nitpick: I modified "currentAssignment" in this method. introduction of "currentAssignmentCopy" do: currentAssignmentCopy.putIfAbsent(instance, new HashSet<>()); move initialization of "currentAssignmentCopy" for loop</technical_language>

Target:
public Map<String, Set<DatastreamTask>> assign(List<DatastreamGroup> datastreams, List<String> instances, Map<String, Set<DatastreamTask>> currentAssignment) { LOG.info("Trying to assign datastreams to instances and the current assignment is {}", datastreams, instances, currentAssignment); Map<String, Set<DatastreamTask>> newAssignment = new HashMap<>(); Map<String, Set<DatastreamTask>> currentAssignmentCopy = new HashMap<>(currentAssignment.size()); currentAssignment.forEach((k, v) -> currentAssignmentCopy.put(k, new HashSet<>(v))); for (String instance : instances) { newAssignment.put(instance, new HashSet<>()); currentAssignmentCopy.putIfAbsent(instance, new HashSet<>()); } int instancePos = 0; for (DatastreamGroup dg : datastreams) { int numTasks = getNumTasks(dg, instances.size()); for (int taskPos = 0; taskPos < numTasks; taskPos++) { String instance = instances.get(instancePos); DatastreamTask foundDatastreamTask = currentAssignmentCopy.get(instance) .stream() .filter(x -> x.getTaskPrefix().equals(dg.getTaskPrefix())) .findFirst() .orElse(new DatastreamTaskImpl(dg.getDatastreams())); currentAssignmentCopy.get(instance).remove(foundDatastreamTask); newAssignment.get(instance).add(foundDatastreamTask); instancePos = (instancePos + 1) % instances.size(); } } LOG.info("New assignment is {}", newAssignment); return newAssignment; }
Source:
<code>public List<TopicPartition> partitions() { <START> return Builder.getPartitions(data); <END> }</code><technical_language>today calling this func once, if in future call multiple times pay cycles time parse map list. cache parsed list locally is called avoid Builder.getPartitions</technical_language>

Target:
public List<TopicPartition> partitions() { if (cachedPartitions != null) { return cachedPartitions; } cachedPartitions = Builder.getPartitions(data); return cachedPartitions; }