auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void shouldCreateEncounterWithGivenParametersWithObsWithManyValues() { Location location = new Location(); location.setName("testLocation"); Patient patient = new Patient(); patient.setUuid("10"); Provider provider = new Provider(); provider.setUuid("20"); Person person = new Person(); person.setUuid("30"); provider.setPerson(person); DateTime encounterDatetime = new DateTime("2000-08-16T07:22:05Z"); Map<String, String> observations = new HashMap<>(); observations.put("testConceptName","testObservationValueName0, testObservationValueName1"); <START> List<Observation> obsList = createObservationListWithManyObservations(); <END> Encounter encounter = new Encounter(location, new EncounterType("testEncounterType"), encounterDatetime.toDate(), patient, Collections.singletonList(provider.getPerson()), obsList); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); doReturn(provider).when(providerService).getProviderByUuid(eq(CONFIG_NAME), eq(provider.getUuid())); doReturn(Collections.singletonList(location)) .when(locationService).getLocations(eq(CONFIG_NAME), eq(location.getName())); openMRSActionProxyService.createEncounter(CONFIG_NAME, new DateTime(encounter.getEncounterDatetime()), encounter.getEncounterType().getName(), location.getName(), patient.getUuid(), provider.getUuid(), observations); verify(encounterService).createEncounter(eq(CONFIG_NAME), encounterCaptor.capture()); assertEquals(encounter, encounterCaptor.getValue()); }</code><technical_language>I existing method createObservationList add a parameter, observations added</technical_language>

Target:
public void shouldCreateEncounterWithGivenParametersWithObsWithManyValues() { Location location = new Location(); location.setName("testLocation"); Patient patient = new Patient(); patient.setUuid("10"); Provider provider = new Provider(); provider.setUuid("20"); Person person = new Person(); person.setUuid("30"); provider.setPerson(person); DateTime encounterDatetime = new DateTime("2000-08-16T07:22:05Z"); Map<String, String> observations = new HashMap<>(); observations.put("testConceptName","testObservationValueName0, testObservationValueName1"); List<Observation> obsList = createObservationList(2); Encounter encounter = new Encounter(location, new EncounterType("testEncounterType"), encounterDatetime.toDate(), patient, Collections.singletonList(provider.getPerson()), obsList); doReturn(patient).when(patientService).getPatientByUuid(eq(CONFIG_NAME), eq(patient.getUuid())); doReturn(provider).when(providerService).getProviderByUuid(eq(CONFIG_NAME), eq(provider.getUuid())); doReturn(Collections.singletonList(location)) .when(locationService).getLocations(eq(CONFIG_NAME), eq(location.getName())); openMRSActionProxyService.createEncounter(CONFIG_NAME, new DateTime(encounter.getEncounterDatetime()), encounter.getEncounterType().getName(), location.getName(), patient.getUuid(), provider.getUuid(), observations); verify(encounterService).createEncounter(eq(CONFIG_NAME), encounterCaptor.capture()); assertEquals(encounter, encounterCaptor.getValue()); }
Source:
<code>public <T> Mono<T> getComponent(String digitalTwinId, String componentPath, Class<T> clazz) { return getComponentWithResponse(digitalTwinId, componentPath, clazz) <START> .flatMap(response -> Mono.justOrEmpty(response.getValue())); <END> }</code><technical_language>this .map</technical_language>

Target:
public <T> Mono<T> getComponent(String digitalTwinId, String componentPath, Class<T> clazz) { return getComponentWithResponse(digitalTwinId, componentPath, clazz) .map(DigitalTwinsResponse::getValue); }
Source:
<code>public CompletableFuture<LogReplicationEntry> sendWithBuffering(LogReplicationEntry message) { message.getMetadata().setSnapshotSyncSeqNum(maxAckedMsgSeqNum++); pendingMessages.append(message); <START> log.info("Send messsage {}", message.getMetadata()); <END> CompletableFuture<LogReplicationEntry> cf = dataSender.send(message); addCFToAcked(message, cf); return cf; }</code><technical_language>I remove this downgrade trace log right sending</technical_language>

Target:
public CompletableFuture<LogReplicationEntry> sendWithBuffering(LogReplicationEntry message) { message.getMetadata().setSnapshotSyncSeqNum(maxAckedMsgSeqNum++); pendingMessages.append(message); log.trace("Send messsage {}", message.getMetadata()); CompletableFuture<LogReplicationEntry> cf = dataSender.send(message); addCFToAcked(message, cf); return cf; }
Source:
<code>public WAL.Entry filter(WAL.Entry entry) { byte[] tableName = entry.getKey().getTablename().getName(); <START> if (!SchemaUtil.isMetaTable(tableName) && !SchemaUtil.isChildLinkTable(tableName)){ <END> return entry; } List<Cell> cells = entry.getEdit().getCells(); List<Cell> cellsToRemove = Lists.newArrayList(); for (Cell cell : cells) { if (!isTenantRowCell(cell)){ cellsToRemove.add(cell); } } cells.removeAll(cellsToRemove); if (cells.size() > 0) { return entry; } else { return null; } }</code><technical_language>safe turn normal HBase replication new System.CHILD_LINK? (That is, is unwanted data in System.CHILD_LINK this WALFilter copy normal HBase replication would?) If normal HBase replication works for System.CHILD_LINK, view data left in System.Catalog starts tenant_id, logic greatly simplified, similar PHOENIX-4229</technical_language>

Target:
public WAL.Entry filter(WAL.Entry entry) { byte[] tableName = entry.getKey().getTablename().getName(); if (!SchemaUtil.isMetaTable(tableName)){ return entry; } List<Cell> cells = entry.getEdit().getCells(); List<Cell> cellsToRemove = Lists.newArrayList(); for (Cell cell : cells) { if (!isTenantRowCell(cell)){ cellsToRemove.add(cell); } } cells.removeAll(cellsToRemove); if (cells.size() > 0) { return entry; } else { return null; } }
Source:
<code>private void backgroundLookup() { <START> new Thread() { <END> public void run() { cache.set(lookup.lookup()); } }.start(); }</code><technical_language>want consider a ThreadPool prevent a large number of threads created</technical_language>

Target:
private void backgroundLookup() { THREAD_POOL.submit(new Runnable() { public void run() { cache.set(lookup.lookup()); } }); }
Source:
<code><START> public DataObject fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException { <END> return null; }</code><technical_language>I a DTO needs returned; implement this method</technical_language>

Target:
public Void fromBundleRequestInput(final ActionRequestDto bundleInput) throws ProtocolAdapterException { this.checkActionRequestType(bundleInput); return null; }
Source:
<code>protected void testFailure(TestDescriptor testDescriptor, TestResult result) { try { <START> if (result.getExceptions() instanceof AssertionError) <END> testResultRecorder.recordTestResult(testDescriptor.getName(), 0, 1, 0, result.getException(), calculateExecutionTimeInSeconds(result)); else testResultRecorder.recordTestResult(testDescriptor.getName(), 0, 0, 1, result.getException(), calculateExecutionTimeInSeconds(result)); } catch (IOException e) { throw new RuntimeException(e); } }</code><technical_language>minor point: add braces { } if/else branch. a convention</technical_language>

Target:
protected void testFailure(TestDescriptor testDescriptor, TestResult result) { String testName = testDescriptor.getName(); Throwable throwable = result.getException(); long executionTime = calculateExecutionTimeInSeconds(result); try { if (throwable instanceof AssertionError) { testResultRecorder.recordTestResult(testName, 0, 1, 0, throwable, executionTime); } else { testResultRecorder.recordTestResult(testName, 0, 0, 1, throwable, executionTime); } } catch (IOException e) { throw new RuntimeException(e); } }
Source:
<code>public boolean isNoexcept(boolean inCalledContext) { if (fOperator == op_throw) return false; ICPPFunction overload = getOverload(); if (overload != null) { <START> return EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier()); <END> } return fArgument.isNoexcept(inCalledContext); }</code><technical_language>(overload is noexcept) && (argument is noexcept)</technical_language>

Target:
public boolean isNoexcept(boolean inCalledContext) { if (fOperator == op_throw) return false; ICPPFunction overload = getOverload(); if (overload != null) { if (!EvalUtil.evaluateNoexceptSpecifier(overload.getType().getNoexceptSpecifier())) return false; } return fArgument.isNoexcept(inCalledContext); }
Source:
<code>private void triggerConnect() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { Optional<Credentials> credentials = OptionalProduct.all( <START> Optional.ofNullable(emailField.getText()).map(String::trim).filter(s -> !s.isEmpty()), <END> Optional.of(new String(passwordField.getPassword())).filter(s -> !s.isEmpty()) ).map(Credentials::new); URL baseUrl = new URL(urlField.getText()); CentralServer server = CentralServer.of( baseUrl, parseInt(projectIdField.getText()), credentials.orElseThrow(BriefcaseException::new) ); onConnectCallbacks.forEach(callback -> callback.accept(server)); } catch (BriefcaseException e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); errorMessage("Invalid Central configuration", "Please, check data and try again.\n\nError: " + e.getCause().getMessage()); } catch (MalformedURLException e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); errorMessage("Invalid Central configuration", "Malformed URL. Please, review data and try again.\n\nError: " + e.getMessage()); } }</code><technical_language>some point, remove this duplication? <img width="1537" alt="Screen Shot 2019-07-28 1 03 46 PM" src="<LINK_0>"></technical_language>

Target:
private void triggerConnect() { setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR)); try { URL baseUrl = new URL(urlField.getText()); CentralServer server = CentralServer.of( baseUrl, parseInt(projectIdField.getText()), UI.credentialsFromFields(emailField, passwordField).orElseThrow(BriefcaseException::new) ); onConnectCallbacks.forEach(callback -> callback.accept(server)); } catch (BriefcaseException e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); errorMessage("Invalid Central configuration", "Please, check data and try again.\n\nError: " + e.getCause().getMessage()); } catch (MalformedURLException e) { setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR)); errorMessage("Invalid Central configuration", "Malformed URL. Please, review data and try again.\n\nError: " + e.getMessage()); } }
Source:
<code>private DTLSMessage handshakeMessageFromByteArray(byte[] decryptedMessage) throws GeneralSecurityException, HandshakeException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Decrypting HANDSHAKE message ciphertext{}{}", StringUtil.lineSeparator(), StringUtil.byteArray2HexString(decryptedMessage)); } HandshakeParameter parameter = null; if (incomingSession != null) { parameter = incomingSession.getParameter(); } else { LOGGER.debug("Parsing message without a session"); } if (LOGGER.isDebugEnabled()) { StringBuilder msg = new StringBuilder("Parsing HANDSHAKE message plaintext [{}]"); if (LOGGER.isTraceEnabled()) { msg.append(":").append(StringUtil.lineSeparator()).append(StringUtil.byteArray2HexString(decryptedMessage)); } LOGGER.debug(msg.toString(), parameter); } HandshakeMessage handshakeMessage = HandshakeMessage.fromByteArray(decryptedMessage, parameter, getPeerAddress()); if (handshakeMessage.getMessageType() == HandshakeType.FINISHED && epoch == 0) { LOGGER.debug("FINISH with epoch 0 from peer [{}]!", peerAddress); AlertMessage alert = new AlertMessage(AlertLevel.FATAL, AlertDescription.UNEXPECTED_MESSAGE, peerAddress); throw new HandshakeException("FINISH with epoch 0!", alert); } <START> return handshakeMessage; <END> }</code><technical_language>sounds Handshaker logic I move in Handshaker :thinking:</technical_language>

Target:
private DTLSMessage handshakeMessageFromByteArray(byte[] decryptedMessage) throws GeneralSecurityException, HandshakeException { if (LOGGER.isTraceEnabled()) { LOGGER.trace("Decrypting HANDSHAKE message ciphertext{}{}", StringUtil.lineSeparator(), StringUtil.byteArray2HexString(decryptedMessage)); } HandshakeParameter parameter = null; if (incomingSession != null) { parameter = incomingSession.getParameter(); } else { LOGGER.debug("Parsing message without a session"); } if (LOGGER.isDebugEnabled()) { StringBuilder msg = new StringBuilder("Parsing HANDSHAKE message plaintext [{}]"); if (LOGGER.isTraceEnabled()) { msg.append(":").append(StringUtil.lineSeparator()).append(StringUtil.byteArray2HexString(decryptedMessage)); } LOGGER.debug(msg.toString(), parameter); } return HandshakeMessage.fromByteArray(decryptedMessage, parameter, getPeerAddress()); }
Source:
<code>private void migrateSingleAccountNumbers(Account account, Organization destinationOrganization) { List<IncomingPhoneNumber> incomingPhoneNumbers = dao.getIncomingPhoneNumbers(account.getSid()); if(incomingPhoneNumbers != null) { for (int i=0; i<incomingPhoneNumbers.size(); i++){ IncomingPhoneNumber incomingPhoneNumber = incomingPhoneNumbers.get(i); incomingPhoneNumber.setOrganizationSid(destinationOrganization.getSid()); dao.updateIncomingPhoneNumber(incomingPhoneNumber); if(!updateNumberAtPhoneNumberProvisioningManager(incomingPhoneNumber, destinationOrganization)){ <START> logger.error(String.format("could not update numner %s at number provider %s ", incomingPhoneNumber.getPhoneNumber(), phoneNumberProvisioningManager)); <END> } } } }</code><technical_language>error level is much. INFO WARN enough i think..</technical_language>

Target:
private void migrateSingleAccountNumbers(Account account, Organization destinationOrganization) { List<IncomingPhoneNumber> incomingPhoneNumbers = dao.getIncomingPhoneNumbers(account.getSid()); if(incomingPhoneNumbers != null) { for (int i=0; i<incomingPhoneNumbers.size(); i++){ IncomingPhoneNumber incomingPhoneNumber = incomingPhoneNumbers.get(i); incomingPhoneNumber.setOrganizationSid(destinationOrganization.getSid()); dao.updateIncomingPhoneNumber(incomingPhoneNumber); if(!updateNumberAtPhoneNumberProvisioningManager(incomingPhoneNumber, destinationOrganization)){ logger.error(String.format("could not update number %s at number provider %s ", incomingPhoneNumber.getPhoneNumber(), phoneNumberProvisioningManager)); } } } }
Source:
<code>public void registerAuthService(AuthenticationService service) { authList.add(service); <START> StartupServiceUtils.updateServiceCache("business-messaging-auth-mgt", AuthenticationService.class); <END> }</code><technical_language>COMPONENT_NAME here</technical_language>

Target:
public void registerAuthService(AuthenticationService service) { authList.add(service); StartupServiceUtils.updateServiceCache(COMPONENT_NAME, AuthenticationService.class); }
Source:
<code>private static String getTokenFileFromClassloader(Class<?> contextClass, VaadinContext context) throws IOException { String tokenResource = VAADIN_SERVLET_RESOURCES + TOKEN_FILE; Lookup lookup = context.getAttribute(Lookup.class); ResourceProvider resourceProvider = lookup .lookup(ResourceProvider.class); List<URL> classResources = resourceProvider .getApplicationResources(contextClass, tokenResource); List<URL> contextResources = resourceProvider .getApplicationResources(context, tokenResource); <START> List<URL> resources; if (classResources.isEmpty()) { resources = contextResources; } else if (contextResources.isEmpty()) { resources = classResources; } else { resources = new ArrayList<>( classResources.size() + contextResources.size()); resources.addAll(classResources); resources.addAll(contextResources); } URL resource = resources.stream() .filter(url -> !url.getPath().endsWith("jar!/" + tokenResource)) .findFirst().orElse(null); <END> if (resource == null && !resources.isEmpty()) { return getPossibleJarResource(contextClass, context, resources); } return resource == null ? null : FrontendUtils.streamToString(resource.openStream()); }</code><technical_language>suggestion Stream<URL> resourceStream = Stream.of(classResources, contextResources).flatMap(Collection::stream); // Accept resource // 'jar!/META-INF/Vaadin/config/flow-build-info.json' URL resource = resourceStream .filter(url -> !url.getPath().endsWith("jar!/" + tokenResource)) .findFirst().orElse(null);</technical_language>

Target:
private static String getTokenFileFromClassloader(Class<?> contextClass, VaadinContext context) throws IOException { String tokenResource = VAADIN_SERVLET_RESOURCES + TOKEN_FILE; Lookup lookup = context.getAttribute(Lookup.class); ResourceProvider resourceProvider = lookup .lookup(ResourceProvider.class); List<URL> classResources = resourceProvider .getApplicationResources(contextClass, tokenResource); List<URL> contextResources = resourceProvider .getApplicationResources(context, tokenResource); List<URL> resources = Stream .concat(classResources.stream(), contextResources.stream()) .collect(Collectors.toList()); URL resource = resources.stream() .filter(url -> !url.getPath().endsWith("jar!/" + tokenResource)) .findFirst().orElse(null); if (resource == null && !resources.isEmpty()) { return getPossibleJarResource(contextClass, context, resources); } return resource == null ? null : FrontendUtils.streamToString(resource.openStream()); }
Source:
<code>public void setProjectName(String projectName) { fProjectName = projectName; if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } <START> if (fRemoteDirSelected == false) { <END> fLocationText.setText(getDefaultPathDisplayString()); } }</code><technical_language>if (!fRemoteDirSelected) {</technical_language>

Target:
public void setProjectName(String projectName) { fProjectName = projectName; if(fLocationText.getText().equals(EMPTY_STRING)) { fRemoteDirSelected = false; } if (!fRemoteDirSelected) { fLocationText.setText(getDefaultPathDisplayString()); } }
Source:
<code>private boolean matchesFilter(StackTraceElement[] stackTraces) { for (StackTraceElement element : stackTraces) { <START> for (Filter filter : filters ) { <END> if (element.getMethodName().equals(filter.methodName) && element.getClassName().equals(filter.className)) { return true; } } } return false; }</code><technical_language>Rewrite as: String methodName = element.getMethodName(); String className = element.getClassName(); int low= 0; int high= filters.length; while (low < high) { int mid= (low + high) >>> 1; Filter filter = filters[mid]; int c = methodName.compareTo(filter.methodName); if (c == 0) c = className.compareTo(filter.className); if (c == 0) { return true; } else if (c < 0) { high = mid; } else { = mid + 1; } }</technical_language>

Target:
private boolean matchesFilter(StackTraceElement[] stackTraces) { for (StackTraceElement element : stackTraces) { String methodName = element.getMethodName(); String className = element.getClassName(); int low = 0; int high = filters.length; while (low < high) { int mid = (low + high) >>> 1; Filter filter = filters[mid]; int c = methodName.compareTo(filter.methodName); if (c == 0) c = className.compareTo(filter.className); if (c == 0) { return true; } else if (c < 0) { high = mid; } else { low = mid + 1; } } } return false; }
Source:
<code>private BpmnNode jbpmServiceTask(org.eclipse.bpmn2.Task task) { Node<View<ServiceTask>, Edge> node = factoryManager.newNode(task.getId(), ServiceTask.class); ServiceTask definition = node.getContent().getDefinition(); ServiceTaskPropertyReader p = propertyReaderFactory.ofCustom(task) .orElseThrow(() -> new NoSuchElementException("Cannot find WorkItemDefinition for " + task.getName())); definition.setName(p.getServiceTaskName()); <START> Object taskType = definition.getTaskType(); <END> definition.getTaskType().setRawType(p.getServiceTaskName()); definition.setDescription(p.getServiceTaskDescription()); definition.setCategory(p.getServiceTaskCategory()); definition.setDefaultHandler(p.getServiceTaskDefaultHandler()); definition.setGeneral(new TaskGeneralSet( new Name(p.getName()), new Documentation(p.getDocumentation()) )); definition.setDataIOSet(new DataIOSet( p.getAssignmentsInfo() )); definition.setExecutionSet(new ServiceTaskExecutionSet( new TaskName(p.getTaskName()), new IsAsync(p.isAsync()), new AdHocAutostart(p.isAdHocAutoStart()), new OnEntryAction(p.getOnEntryAction()), new OnExitAction(p.getOnExitAction()), new SLADueDate(p.getSlaDueDate()) )); definition.setSimulationSet(p.getSimulationSet()); node.getContent().setBounds(p.getBounds()); definition.setDimensionsSet(p.getRectangleDimensionsSet()); definition.setBackgroundSet(p.getBackgroundSet()); definition.setFontSet(p.getFontSet()); return BpmnNode.of(node, p); }</code><technical_language>add this line of code? taskType var is used</technical_language>

Target:
private BpmnNode jbpmServiceTask(org.eclipse.bpmn2.Task task) { return propertyReaderFactory .ofCustom(task) .map(p -> { final Node<View<ServiceTask>, Edge> node = factoryManager.newNode(task.getId(), ServiceTask.class); final ServiceTask definition = node.getContent().getDefinition(); definition.setName(p.getServiceTaskName()); definition.getTaskType().setRawType(p.getServiceTaskName()); definition.setDescription(p.getServiceTaskDescription()); definition.setCategory(p.getServiceTaskCategory()); definition.setDefaultHandler(p.getServiceTaskDefaultHandler()); definition.setGeneral(new TaskGeneralSet( new Name(p.getName()), new Documentation(p.getDocumentation()) )); definition.setDataIOSet(new DataIOSet( p.getAssignmentsInfo() )); definition.setExecutionSet(new ServiceTaskExecutionSet( new TaskName(p.getTaskName()), new IsAsync(p.isAsync()), new AdHocAutostart(p.isAdHocAutoStart()), new OnEntryAction(p.getOnEntryAction()), new OnExitAction(p.getOnExitAction()), new SLADueDate(p.getSlaDueDate()) )); definition.setSimulationSet(p.getSimulationSet()); node.getContent().setBounds(p.getBounds()); definition.setDimensionsSet(p.getRectangleDimensionsSet()); definition.setBackgroundSet(p.getBackgroundSet()); definition.setFontSet(p.getFontSet()); return BpmnNode.of(node, p); }) .orElseGet(() -> noneTask(task)); }
Source:
<code>private void processPriorityEvents() throws IOException, InterruptedException { final boolean hasPriorityEvents = inputGate.getPriorityEventAvailableFuture().isDone(); if (hasPriorityEvents) { END> <START> while (pollNext().map(BufferOrEvent::morePriorityEvents).orElse(false)) { } } waitForPriorityEvents(inputGate, mailboxExecutor); }</code><technical_language>I understand it, assumes this pollNext() return else besides a priority event</technical_language>

Target:
private void processPriorityEvents() throws IOException, InterruptedException { boolean hasPriorityEvent = inputGate.getPriorityEventAvailableFuture().isDone(); while (hasPriorityEvent) { final Optional<BufferOrEvent> bufferOrEventOpt = pollNext(); checkState(bufferOrEventOpt.isPresent()); final BufferOrEvent bufferOrEvent = bufferOrEventOpt.get(); checkState(bufferOrEvent.hasPriority(), "Should only poll priority events"); hasPriorityEvent = bufferOrEvent.morePriorityEvents(); } waitForPriorityEvents(inputGate, mailboxExecutor); }
Source:
<code>public void addChild(Widget widget) { switch (layout) { case ONE_COLUMN: addChildOneColumn(widget); break; case TWO_COLUMNS: addChildTwoColumns(widget); break; default: <START> Info.display("DynamicLayoutPanel", "addChild with layout " + layout + " not yet implemented"); <END> } }</code><technical_language>is intended so</technical_language>

Target:
public void addChild(Widget widget) { switch (layout) { case TWO_COLUMNS: addChildTwoColumns(widget); break; default: addChildOneColumn(widget); } }
Source:
<code>private void removeAppBar() { DWORD dwABM = new DWORD(); APPBARDATA ABData = new APPBARDATA.ByReference(); ABData.cbSize.setValue( ABData.size() ); dwABM.setValue(ShellAPI.ABM_REMOVE); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage( dwABM, ABData); <START> assertNotNull(result ); <END> }</code><technical_language>Another extra space, plese cleanup similar things? a others, some functions spaces in parameters, some queryPos( APPBARDATA ABData ) vs. dwABM.setValue(ShellAPI.ABM_QUERYPOS);. a pest, messy inconsistent</technical_language>

Target:
private void removeAppBar() { APPBARDATA data = new APPBARDATA.ByReference(); data.cbSize.setValue(data.size()); UINT_PTR result = Shell32.INSTANCE.SHAppBarMessage(new DWORD(ShellAPI.ABM_REMOVE), data); assertNotNull(result); }
Source:
<code>public static RawType valueOf(String value) { int idx; if (value == null || !value.startsWith("data:") || ((idx = value.indexOf(",")) < 0)) { <START> return new RawType(); <END> } String mimeType = DEFAULT_MIME_TYPE; int idx2 = value.indexOf(";"); if (idx2 > 5) { mimeType = value.substring(5, idx2); } return new RawType(Base64.getDecoder().decode(value.substring(idx + 1)), mimeType); }</code><technical_language>here, create a RawType of data, is this accepted throwing exception? Need check other types. Is this common handling ignore a correct "deserialization"</technical_language>

Target:
public static RawType valueOf(String value) { int idx, idx2; if (value == null) { throw new IllegalArgumentException("Argument must not be null"); } else if (value.isEmpty()) { throw new IllegalArgumentException("Argument must not be blank"); } else if (!value.startsWith("data:") || ((idx = value.indexOf(",")) < 0)) { throw new IllegalArgumentException("Invalid data URI syntax for argument " + value); } else if ((idx2 = value.indexOf(";")) <= 5) { throw new IllegalArgumentException("Missing MIME type in argument " + value); } return new RawType(Base64.getDecoder().decode(value.substring(idx + 1)), value.substring(5, idx2)); }
Source:
<code>protected Ehcache<String, String> getEhcache(final CacheLoaderWriter<String, String> cacheLoaderWriter, String name) { ExecutorService orderedExecutor = Executors.newSingleThreadExecutor(); ExecutorService unorderedExecutor = Executors.newCachedThreadPool(); <START> TestTimeSource timeSource = new TestTimeSource(); <END> cacheEventNotificationService = new CacheEventNotificationServiceImpl<String, String>(orderedExecutor, unorderedExecutor, store, timeSource); RuntimeConfiguration<String, String> runtimeConfiguration = new RuntimeConfiguration<String, String>(CACHE_CONFIGURATION, cacheEventNotificationService); final Ehcache<String, String> ehcache = new Ehcache<String, String>(runtimeConfiguration, this.store, cacheLoaderWriter, cacheEventNotificationService, LoggerFactory.getLogger(Ehcache.class + "-" + name)); ehcache.init(); assertThat("cache not initialized", ehcache.getStatus(), CoreMatchers.is(Status.AVAILABLE)); registerCacheEventListener(ehcache, cacheEventListener); return ehcache; }</code><technical_language>do introduce a TestTimeSource here? Is SystemTimeSource is in scope lives in impl module? Especially TestTimeSource provides advanceTime method is - dead code. options: - Move SystemTimeSource fromimpltocore - anonymous class wraps System.currentTimeMillis()</technical_language>

Target:
protected Ehcache<String, String> getEhcache(final CacheLoaderWriter<String, String> cacheLoaderWriter, String name) { ExecutorService orderedExecutor = Executors.newSingleThreadExecutor(); ExecutorService unorderedExecutor = Executors.newCachedThreadPool(); TimeSource timeSource = SystemTimeSource.INSTANCE; cacheEventNotificationService = new CacheEventNotificationServiceImpl<String, String>(orderedExecutor, unorderedExecutor, store, timeSource); RuntimeConfiguration<String, String> runtimeConfiguration = new RuntimeConfiguration<String, String>(CACHE_CONFIGURATION, cacheEventNotificationService); final Ehcache<String, String> ehcache = new Ehcache<String, String>(runtimeConfiguration, this.store, cacheLoaderWriter, cacheEventNotificationService, LoggerFactory.getLogger(Ehcache.class + "-" + name)); ehcache.init(); assertThat("cache not initialized", ehcache.getStatus(), CoreMatchers.is(Status.AVAILABLE)); registerCacheEventListener(ehcache, cacheEventListener); return ehcache; }
Source:
<code>public void testScrollToWithTwoArguments() { final Element element = mock(Element.class); <START> doNothing().when(scrollHelper).scrollTo(element, element, 0); <END> scrollHelper.scrollTo(element, element); verify(scrollHelper).scrollTo(element, element, 0); }</code><technical_language>I tend prefer passing values/mocks for parameters verify correct parameters assertion (who's implementation of scrollHelper.scrollTo(e1, e2) swap parameters around!? this test</technical_language>

Target:
public void testScrollToWithTwoArguments() { final Element target = mock(Element.class); final Element container = mock(Element.class); doNothing().when(scrollHelper).scrollTo(any(), any(), anyInt()); scrollHelper.scrollTo(target, container); verify(scrollHelper).scrollTo(target, container, 0); }
Source:
<code>private void loadIndicator(final WebElement element) { <START> String aClass = element.getAttribute("class"); <END> if (StringUtils.contains(aClass, "error")) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.ERROR; } else if (StringUtils.contains(aClass, "warn")) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.WARN; } else if (StringUtils.contains(aClass, "info")) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.INFO; } else if (StringUtils.contains(aClass, "success")) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.SUCCESS; } }</code><technical_language>a note class names used. full class names in a fixed format (e.g.wc-fieldindicator-type-error shorter version ensure classes. a huge issue worth considering. move actual String values private class members intending move Java for rendering in case handy if extend this WebElement further</technical_language>

Target:
private void loadIndicator(final WebElement element) { String aClass = element.getAttribute("class"); if (StringUtils.contains(aClass, FIELD_INDICATOR_CLASS_ERROR)) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.ERROR; } else if (StringUtils.contains(aClass, FIELD_INDICATOR_CLASS_WARN)) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.WARN; } else if (StringUtils.contains(aClass, FIELD_INDICATOR_CLASS_INFO)) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.INFO; } else if (StringUtils.contains(aClass, FIELD_INDICATOR_CLASS_SUCCESS)) { indicatorType = AbstractWFieldIndicator.FieldIndicatorType.SUCCESS; } }
Source:
<code>public void adsIncontentLeaderboard(String wikiName, String article) { String url = urlBuilder.getUrlForPath(wikiName, article); url = urlBuilder.appendQueryStringToURL(url, URL_PARAM_ENABLE_SITEWIDE); new AdsBaseObject(driver, url) .triggerAdSlot(AdsContent.INCONTENT_LEADERBOARD) <START> .waitForCSSPseudoElementsContentToMatchValue("#"+AdsContent.INCONTENT_LEADERBOARD, <END> "before", "\"advertisement\""); }</code><technical_language>Nitpicking: a pattern String.format() more readable instead of concatenating that. do it</technical_language>

Target:
public void adsIncontentLeaderboard(String wikiName, String article) { String url = urlBuilder.getUrlForPath(wikiName, article); url = urlBuilder.appendQueryStringToURL(url, URL_PARAM_ENABLE_SITEWIDE); AdsBaseObject adsBaseObject = new AdsBaseObject(driver, url) .triggerAdSlot(AdsContent.INCONTENT_LEADERBOARD); String slotLabel = adsBaseObject.getPseudoElementValue( driver.findElement(By.cssSelector(AdsContent.getSlotSelector(AdsContent.INCONTENT_LEADERBOARD))), "before", "content"); Assertion.assertEquals(slotLabel, "\"advertisement\""); }
Source:
<code>public Expression<?> visit(Path<?> expr, Context context) { if (expr.getMetadata().getPathType() == PathType.COLLECTION_ANY) { Path<?> parent = (Path<?>) expr.getMetadata().getParent().accept(this, context); expr = new PathImpl<Object>(expr.getType(), PathMetadataFactory.forCollectionAny(parent)); EntityPath<?> replacement = new EntityPathBase<Object>(expr.getType(), ExpressionUtils.createRootVariable(expr, replaced.size())); context.add(expr, replacement); <START> replaced.add(expr); <END> return replacement; } else if (expr.getMetadata().getParent() != null) { Context c = new Context(); Path<?> parent = (Path<?>) expr.getMetadata().getParent().accept(this, c); if (c.replace) { context.add(c); return replaceParent(expr, parent); } } return expr; }</code><technical_language>replaced grow</technical_language>

Target:
public Expression<?> visit(Path<?> expr, Context context) { if (expr.getMetadata().getPathType() == PathType.COLLECTION_ANY) { Path<?> parent = (Path<?>) expr.getMetadata().getParent().accept(this, context); expr = new PathImpl<Object>(expr.getType(), PathMetadataFactory.forCollectionAny(parent)); EntityPath<?> replacement = new EntityPathBase<Object>(expr.getType(), ExpressionUtils.createRootVariable(expr, replacedCounter++)); context.add(expr, replacement); return replacement; } else if (expr.getMetadata().getParent() != null) { Context c = new Context(); Path<?> parent = (Path<?>) expr.getMetadata().getParent().accept(this, c); if (c.replace) { context.add(c); return replaceParent(expr, parent); } } return expr; }
Source:
<code>public void setAdditionalExceptionMappings(Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings){ Assert.notEmpty(mappings, "The mappings Map must not be empty nor null"); for (Map.Entry<Class<? extends AuthenticationException>,Class<? extends AbstractAuthenticationFailureEvent>> entry : mappings.entrySet()) { Class<?> exceptionClazz = entry.getKey(); Class<?> eventClazz = entry.getValue(); <START> Assert.isAssignable(AuthenticationException.class, exceptionClazz); <END> Assert.isAssignable(AbstractAuthenticationFailureEvent.class, eventClazz); addMapping(exceptionClazz.getName(), (Class<? extends AbstractAuthenticationFailureEvent>) eventClazz); } }</code><technical_language>Is a reason checking isAssignable? parameter types for Map this for you. I if bypasses parameter types erasure something, do peril. of more like: java Class<? extends AuthenticationException> exceptionClass = entry.getKey(); Assert.notNull(exceptionClass, "exceptionClass null");</technical_language>

Target:
public void setAdditionalExceptionMappings(Map<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> mappings){ Assert.notEmpty(mappings, "The mappings Map must not be empty nor null"); for (Map.Entry<Class<? extends AuthenticationException>, Class<? extends AbstractAuthenticationFailureEvent>> entry : mappings.entrySet()) { Class<?> exceptionClass = entry.getKey(); Class<?> eventClass = entry.getValue(); Assert.notNull(exceptionClass, "exceptionClass cannot be null"); Assert.notNull(eventClass, "eventClass cannot be null"); addMapping(exceptionClass.getName(), (Class<? extends AbstractAuthenticationFailureEvent>) eventClass); } }
Source:
<code>protected FileImporterContext(Builder builder) { session = builder.session; blob = builder.blob; parentPath = builder.parentPath; overwrite = builder.overwrite; mimeTypeCheck = builder.mimeTypeCheck; excludeOneToMany = builder.excludeOneToMany; <START> fileName = StringUtils.isNotEmpty(builder.fileName) ? builder.fileName : blob.getFilename(); <END> persistDocument = builder.persistDocument; }</code><technical_language>StringUtils#defaultIfEmpty instead of ternary expression</technical_language>

Target:
protected FileImporterContext(Builder builder) { session = builder.session; blob = builder.blob; parentPath = builder.parentPath; overwrite = builder.overwrite; mimeTypeCheck = builder.mimeTypeCheck; excludeOneToMany = builder.excludeOneToMany; fileName = StringUtils.defaultIfEmpty(builder.fileName, blob.getFilename()); persistDocument = builder.persistDocument; }
Source:
<code>public QueryResultCachePlugin( SolrCache solrCache, SolrCacheSource solrCacheSource, ExecutorService solrCacheExecutorService) { cacheSource = solrCacheSource; cacheExecutorService = solrCacheExecutorService; cacheCommitPhaser = new CacheCommitPhaser(solrCache); cacheBulkProcessor = new CacheBulkProcessor(solrCache); <START> } <END></code><technical_language>Do need null checks for of in ctor</technical_language>

Target:
public QueryResultCachePlugin( SolrCache solrCache, SolrCacheSource solrCacheSource, ExecutorService solrCacheExecutorService) { Validate.notNull(solrCache, "Valid SolrCache required."); Validate.notNull(solrCacheSource, "Valid SolrCacheSource required."); Validate.notNull(solrCacheExecutorService, "Valid ExecutorService required."); cacheSource = solrCacheSource; cacheExecutorService = solrCacheExecutorService; cacheBulkProcessor = new CacheBulkProcessor(solrCache); }
Source:
<code>public URI buildEncoded() { for (int i = 0; i < qParams.size(); i++) { String amp = (i != qParams.size() - 1) ? "&" : ""; query.append(qParams.get(i) + amp); } try { String q = (query.length() == 0) ? "" : "?" + query; <START> String uri = String.format("%s://%s:%s%s%s%s", new Object[]{scheme, host, port, path, encodedPath, q}); <END> return new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }</code><technical_language>I this in change varargs syntax instead (remove new Object[]{})</technical_language>

Target:
public URI buildEncoded() { for (int i = 0; i < qParams.size(); i++) { String amp = (i != qParams.size() - 1) ? "&" : ""; query.append(qParams.get(i).toURLEncodedString() + amp); } try { String q = (query.length() == 0) ? "" : "?" + query; String uri = String.format("%s://%s:%s%s%s%s", scheme, host, port, path, encodedPath, q); return new URI(uri); } catch (URISyntaxException e) { throw new IllegalArgumentException(e); } }
Source:
<code>public void createAuxiliaryConnections(Set<Integer> peers, int secondaryConnections) { <START> m_numberOfConnections = secondaryConnections + 1; <END> for (int hostId : peers) { if (hostId == m_localHostId) { continue; } for (int ii = 0; ii < secondaryConnections; ii++) { Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { ForeignHost fh = it.next(); try { SocketChannel socket = m_joiner.requestForConnection(fh.m_listeningAddress); ForeignHost fhost = new ForeignHost(this, hostId, socket, Integer.MAX_VALUE, fh.m_listeningAddress, new PicoNetwork(socket)); putForeignHost(hostId, fhost); fhost.enableRead(VERBOTEN_THREADS); } catch (Exception e) { m_hostLog.error("Failed to connect to peer nodes.", e); throw new RuntimeException("Failed to establish socket connection with " + fh.m_listeningAddress.getAddress().getHostAddress(), e); } } } } }</code><technical_language>@luyangco update m_numberOfConnections end of this function secondaryConnections successfully created, in case of exceptions happened</technical_language>

Target:
public void createAuxiliaryConnections(Set<Integer> peers, int secondaryConnections) { for (int hostId : peers) { for (int ii = 0; ii < secondaryConnections; ii++) { Iterator<ForeignHost> it = m_foreignHosts.get(hostId).iterator(); if (it.hasNext()) { ForeignHost fh = it.next(); try { SocketChannel socket = m_joiner.requestForConnection(fh.m_listeningAddress); ForeignHost fhost = new ForeignHost(this, hostId, socket, Integer.MAX_VALUE, fh.m_listeningAddress, new PicoNetwork(socket)); putForeignHost(hostId, fhost); fhost.enableRead(VERBOTEN_THREADS); } catch (Exception e) { m_hostLog.error("Failed to connect to peer nodes.", e); throw new RuntimeException("Failed to establish socket connection with " + fh.m_listeningAddress.getAddress().getHostAddress(), e); } } } } m_hasAllSecondaryConnectionCreated = true; }
Source:
<code>public Long getNextSequenceValue() { <START> return nextSequenceValue == null ? -1l : nextSequenceValue; <END> }</code><technical_language>Is this a formatting change</technical_language>

Target:
public Long getNextSequenceValue() { if(nextSequenceValue == null) return -1l; return nextSequenceValue; }
Source:
<code>public void test() { SpillCipher cipher = new AesSpillCipher(); PagesSerde serde = new TestingPagesSerdeFactory().createPagesSerdeForSpill(Optional.of(cipher)); List<Type> types = ImmutableList.of(VARCHAR); <START> Page empty = new Page(VARCHAR.createBlockBuilder(null, 0).build()); <END> assertPageEquals(types, serde.deserialize(serde.serialize(empty)), empty); BlockBuilder blockBuilder = VARCHAR.createBlockBuilder(null, 2); VARCHAR.writeString(blockBuilder, "hello"); VARCHAR.writeString(blockBuilder, "world"); Page nonEmpty = new Page(blockBuilder.build()); SerializedPage serialized = serde.serialize(nonEmpty); assertPageEquals(types, serde.deserialize(serialized), nonEmpty); assertTrue(ENCRYPTED.isSet(serialized.getPageCodecMarkers()), "page should be encrypted"); cipher.destroy(); assertFailure(() -> serde.serialize(nonEmpty), "Spill cipher already destroyed"); assertFailure(() -> serde.deserialize(serialized), "Spill cipher already destroyed"); }</code><technical_language>nit: s/empty/emptyPage</technical_language>

Target:
public void test() { SpillCipher cipher = new AesSpillCipher(); PagesSerde serde = new TestingPagesSerdeFactory().createPagesSerdeForSpill(Optional.of(cipher)); List<Type> types = ImmutableList.of(VARCHAR); Page emptyPage = new Page(VARCHAR.createBlockBuilder(null, 0).build()); assertPageEquals(types, serde.deserialize(serde.serialize(emptyPage)), emptyPage); BlockBuilder blockBuilder = VARCHAR.createBlockBuilder(null, 2); VARCHAR.writeString(blockBuilder, "hello"); VARCHAR.writeString(blockBuilder, "world"); Page helloWorldPage = new Page(blockBuilder.build()); SerializedPage serialized = serde.serialize(helloWorldPage); assertPageEquals(types, serde.deserialize(serialized), helloWorldPage); assertTrue(ENCRYPTED.isSet(serialized.getPageCodecMarkers()), "page should be encrypted"); cipher.destroy(); assertFailure(() -> serde.serialize(helloWorldPage), "Spill cipher already destroyed"); assertFailure(() -> serde.deserialize(serialized), "Spill cipher already destroyed"); }
Source:
<code><START> public void testApplicationBinding_noPrevious_noImportAdded() throws IllegalAccessException, InterruptedException { <END> AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getTomcatVm(); Assert.assertEquals( 0, processor.applicationBindings.size()); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); MsgCmdChangeBinding msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( new HashSet<>( Arrays.asList( "demo" )), processor.applicationBindings.get( "ext" )); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); }</code><technical_language>No, this method throw interrupted exceptions</technical_language>

Target:
public void testApplicationBinding_noPrevious_noImportAdded() throws IllegalAccessException { AgentMessageProcessor processor = (AgentMessageProcessor) this.agent.getMessagingClient().getMessageProcessor(); TestApplicationTemplate app = new TestApplicationTemplate(); processor.scopedInstance = app.getTomcatVm(); Assert.assertEquals( 0, processor.applicationBindings.size()); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); MsgCmdChangeBinding msg = new MsgCmdChangeBinding( "ext", new HashSet<>( Arrays.asList( "demo" ))); processor.processMessage( msg ); Assert.assertEquals( 1, processor.applicationBindings.size()); Assert.assertEquals( new HashSet<>( Arrays.asList( "demo" )), processor.applicationBindings.get( "ext" )); Assert.assertEquals( 0, processor.applicationNameToExternalExports.size()); }
Source:
<code>public void onAccountChanged(AccountStore.OnAccountChanged event) { <START> if (!isAdded()) { <END> return; } if (event.isError()) { switch (event.error.type) { case SETTINGS_FETCH_ERROR: ToastUtils .showToast(getActivity(), R.string.error_fetch_account_settings, ToastUtils.Duration.LONG); break; case SETTINGS_POST_ERROR: ToastUtils.showToast(getActivity(), R.string.error_post_account_settings, ToastUtils.Duration.LONG); break; } } updateAnalyticsSyncUI(); }</code><technical_language>if this points a problem, i noticed this is triggered I close app settings, I changes</technical_language>

Target:
public void onAccountChanged(AccountStore.OnAccountChanged event) { if (!isAdded()) { return; } if (event.isError()) { switch (event.error.type) { case SETTINGS_FETCH_ERROR: ToastUtils .showToast(getActivity(), R.string.error_fetch_account_settings, ToastUtils.Duration.LONG); break; case SETTINGS_POST_ERROR: ToastUtils.showToast(getActivity(), R.string.error_post_account_settings, ToastUtils.Duration.LONG); break; } } else if (event.causeOfChange == AccountAction.FETCH_SETTINGS) { updateAnalyticsSyncUI(); } }
Source:
<code>public ProjectApi create(ProjectInput in) throws RestApiException { <START> if(in.name == null) { <END> throw new AssertionError("Name must be set in project creation input."); } String url = String.format("/projects/%s", in.name); String projectInput = projectsParser.generateProjectInput(in); JsonElement result = gerritRestClient.putRequest(url, projectInput); ProjectInfo info = projectsParser.parseSingleProjectInfo(result); return new ProjectApiRestClient(gerritRestClient, projectsParser, branchInfoParser, tagInfoParser, info.name); }</code><technical_language>fine</technical_language>

Target:
public ProjectApi create(ProjectInput in) throws RestApiException { if (in.name == null) { throw new IllegalArgumentException("Name must be set in project creation input."); } String url = String.format("/projects/%s", in.name); String projectInput = projectsParser.generateProjectInput(in); JsonElement result = gerritRestClient.putRequest(url, projectInput); ProjectInfo info = projectsParser.parseSingleProjectInfo(result); return new ProjectApiRestClient(gerritRestClient, projectsParser, branchInfoParser, tagInfoParser, info.name); }
Source:
<code>private List<String> getChildrenCached(final String zkPath) { try { <START> PathChildrenCache cache = SLOTS_CACHES.getOrDefault(zkPath, null); <END> if (cache == null) { cache = new PathChildrenCache(zkHolder.get(), zkPath, false); cache.start(BUILD_INITIAL_CACHE); SLOTS_CACHES.put(zkPath, cache); } return cache.getCurrentData().stream() .map(childData -> { final String[] pathParts = childData.getPath().split("/"); return pathParts[pathParts.length - 1]; }) .collect(toList()); } catch (Exception e) { LOG.error("Zookeeper error when getting consumer nodes", e); throw new NakadiRuntimeException(e); } }</code><technical_language>want curator TreeCache for that? In case store list of caches</technical_language>

Target:
private List<String> getChildrenCached(final String zkPath) { final PathChildrenCache cache = SLOTS_CACHES.computeIfAbsent(zkPath, key -> { try { final PathChildrenCache newCache = new PathChildrenCache(zkHolder.get(), key, false); newCache.start(BUILD_INITIAL_CACHE); return newCache; } catch (final Exception e) { LOG.error("Zookeeper error when getting consumer nodes", e); throw new NakadiRuntimeException(e); } }); return cache.getCurrentData().stream() .map(childData -> { final String[] pathParts = childData.getPath().split("/"); return pathParts[pathParts.length - 1]; }) .collect(toList()); }