auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void setRepo() throws FieldNotFoundException { Map trigger = Optional.ofNullable(event.getContent()) .map(content -> (Map) content.get("execution")) .map(execution -> (Map) execution.get("trigger")) .orElseThrow(FieldNotFoundException::new); if (trigger.containsKey("type") && trigger.get("type").equals("git") <START> && trigger.get("source").equals("github")) { <END> String repo_project = Optional.ofNullable((String) trigger.get("project")) .orElseThrow(FieldNotFoundException::new); String repo_slug = Optional.ofNullable((String) trigger.get("slug")) .orElseThrow(FieldNotFoundException::new); repo = String.format("%s/%s", repo_project, repo_slug); } else { repo = Optional.ofNullable(trigger) .map(t -> (Map) t.get("buildInfo")) .map(buildInfo -> (String) buildInfo.get("name")) .orElseThrow(FieldNotFoundException::new); } }</code><technical_language>I do tests other protect potential NPEs: "github".equals(trigger.get("source"))</technical_language>

Target:
private void setRepo() throws FieldNotFoundException { Map trigger = Optional.ofNullable(event.getContent()) .map(content -> (Map) content.get("execution")) .map(execution -> (Map) execution.get("trigger")) .orElseThrow(FieldNotFoundException::new); if (trigger.containsKey("type") && "git".equals(trigger.get("type")) && "github".equals(trigger.get("source"))) { String repo_project = Optional.ofNullable((String) trigger.get("project")) .orElseThrow(FieldNotFoundException::new); String repo_slug = Optional.ofNullable((String) trigger.get("slug")) .orElseThrow(FieldNotFoundException::new); repo = String.format("%s/%s", repo_project, repo_slug); } else { repo = Optional.ofNullable(trigger) .map(t -> (Map) t.get("buildInfo")) .map(buildInfo -> (String) buildInfo.get("name")) .orElseThrow(FieldNotFoundException::new); } }
Source:
<code>static void validate(Object template, String identifier) { if (!(template instanceof Map)) { return; } Map<String, ?> map = (Map<String, ?>) template; final Map<String, ?> servicesMap; if (map.containsKey("version")) { if (!map.containsKey("services")) { log.debug("Compose file has an unknown format: 'version' is set but 'services' is not defined", identifier); return; } Object services = map.get("services"); if (!(services instanceof Map)) { log.debug("Compose file has an unknown format: 'services' is not Map", identifier); return; } servicesMap = (Map<String, ?>) services; } else { servicesMap = map; } for (Map.Entry<String, ?> entry : servicesMap.entrySet()) { String serviceName = entry.getKey(); Object serviceDefinition = entry.getValue(); if (!(serviceDefinition instanceof Map)) { <START> break; <END> } if (((Map) serviceDefinition).containsKey("container_name")) { throw new IllegalStateException(String.format( "Compose file %s has 'container_name' property set for service '%s' but this property is not supported by Testcontainers, consider removing it", identifier, serviceName )); } } }</code><technical_language>Do break continue abort validation entirely? If breaking, log debug explain encountered unknown format</technical_language>

Target:
static void validate(Object template, String identifier) { if (!(template instanceof Map)) { return; } Map<String, ?> map = (Map<String, ?>) template; final Map<String, ?> servicesMap; if (map.containsKey("version")) { if (!map.containsKey("services")) { log.debug("Compose file has an unknown format: 'version' is set but 'services' is not defined", identifier); return; } Object services = map.get("services"); if (!(services instanceof Map)) { log.debug("Compose file has an unknown format: 'services' is not Map", identifier); return; } servicesMap = (Map<String, ?>) services; } else { servicesMap = map; } for (Map.Entry<String, ?> entry : servicesMap.entrySet()) { String serviceName = entry.getKey(); Object serviceDefinition = entry.getValue(); if (!(serviceDefinition instanceof Map)) { log.debug("Compose file has an unknown format: service '{}' is not Map", identifier, serviceName); break; } if (((Map) serviceDefinition).containsKey("container_name")) { throw new IllegalStateException(String.format( "Compose file %s has 'container_name' property set for service '%s' but this property is not supported by Testcontainers, consider removing it", identifier, serviceName )); } } }
Source:
<code>public void close() { stmts.forEach(stmt -> { try { if (stmt != null && !stmt.isClosed()) { stmt.close(); } } catch (SQLException e) { <START> throw new IllegalStateException(e); <END> } }); try { if (conn != null) { conn.close(); } } catch (SQLException e) { throw new IllegalStateException(e); } }</code><technical_language>close connection throwing exception connection close is handled some place else</technical_language>

Target:
public void close() { stmts.forEach(stmt -> cancelAndCloseSoftly(stmt)); closeSoftly(conn); }
Source:
<code>protected void subscribeActual(Subscriber<? super T> observer) { Collection<? super K> collection; try { <START> collection = ObjectHelper.requireNonNull(collectionSupplier.call(), "The returned Collection is null. Null values are generally not allowed in 2.x operators and sources."); <END> } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptySubscription.error(ex, observer); return; } source.subscribe(new DistinctSubscriber<T, K>(observer, keySelector, collection)); }</code><technical_language>This wording else. "The collectionSupplier returned null."</technical_language>

Target:
protected void subscribeActual(Subscriber<? super T> observer) { Collection<? super K> collection; try { collection = ObjectHelper.requireNonNull(collectionSupplier.call(), "The collectionSupplier returned a null collection. Null values are generally not allowed in 2.x operators and sources."); } catch (Throwable ex) { Exceptions.throwIfFatal(ex); EmptySubscription.error(ex, observer); return; } source.subscribe(new DistinctSubscriber<T, K>(observer, keySelector, collection)); }
Source:
<code>public void stacksDismissibleNotification() { NotificationInformation notificationInfo = createNotificationInfo(STACK_NOTIFICATION_DISMISSIBLE, 100); given(notificationCreator.createNotification(DOWNLOAD_BATCH_STATUS)).willReturn(notificationInfo); notificationDispatcher.updateNotification(DOWNLOAD_BATCH_STATUS); InOrder inOrder = inOrder(downloadService, notificationManager); <START> inOrder.verify(downloadService, never()).stop(true); <END> inOrder.verify(notificationManager).notify(NOTIFICATION_TAG, notificationInfo.getId(), notificationInfo.getNotification()); inOrder.verifyNoMoreInteractions(); }</code><technical_language>Do need inOrder here? checking for a for a single call. if in inOrder</technical_language>

Target:
public void stacksDismissibleNotification() { NotificationInformation notificationInfo = createNotificationInfo(STACK_NOTIFICATION_DISMISSIBLE, 100); given(notificationCreator.createNotification(DOWNLOAD_BATCH_STATUS)).willReturn(notificationInfo); notificationDispatcher.updateNotification(DOWNLOAD_BATCH_STATUS); verify(downloadService, never()).stop(true); verify(notificationManager).notify(NOTIFICATION_TAG, notificationInfo.getId(), notificationInfo.getNotification()); }
Source:
<code>public void testPrometheusJobMetrics() throws Exception { int currentNumberOfCancelled = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.CANCELLED.toString()), 0, 1000).size(); int currentNumberOfDone = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.DONE.toString()), 0, 1000).size(); <START> Calendar tomorrow = Calendar.getInstance(); <END> tomorrow.add(Calendar.DATE, 1); JobRequestInstance jobRequestInstanceTomorrow = createJobRequestInstance(); jobRequestInstanceTomorrow.setScheduledDate(tomorrow.getTime()); Long jobIdTomorrow = jobServicesClient.scheduleRequest(jobRequestInstanceTomorrow); jobServicesClient.cancelRequest(jobIdTomorrow); JobRequestInstance jobRequestInstanceNow = createJobRequestInstance(); Long jobIdNow = jobServicesClient.scheduleRequest(jobRequestInstanceNow); KieServerSynchronization.waitForJobToFinish(jobServicesClient, jobIdNow); assertThat(getMetrics()).contains( "kie_server_job_scheduled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}", "kie_server_job_cancelled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",} " + (currentNumberOfCancelled + 1) ); }</code><technical_language>Nitpicking here. a one-liner more clear</technical_language>

Target:
public void testPrometheusJobMetrics() throws Exception { int currentNumberOfCancelled = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.CANCELLED.toString()), 0, 1000).size(); int currentNumberOfDone = jobServicesClient.getRequestsByStatus(Collections.singletonList(STATUS.DONE.toString()), 0, 1000).size(); Instant tomorrow = Instant.now().plus(1, ChronoUnit.DAYS); JobRequestInstance jobRequestInstanceTomorrow = createJobRequestInstance(); jobRequestInstanceTomorrow.setScheduledDate(Date.from(tomorrow)); Long jobIdTomorrow = jobServicesClient.scheduleRequest(jobRequestInstanceTomorrow); jobServicesClient.cancelRequest(jobIdTomorrow); JobRequestInstance jobRequestInstanceNow = createJobRequestInstance(); Long jobIdNow = jobServicesClient.scheduleRequest(jobRequestInstanceNow); KieServerSynchronization.waitForJobToFinish(jobServicesClient, jobIdNow); assertThat(getMetrics()).contains( "kie_server_job_scheduled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",}", "kie_server_job_cancelled_total{container_id=\"\",command_name=\"" + PRINT_OUT_COMMAND + "\",} " + (currentNumberOfCancelled + 1) ); }
Source:
<code>protected Provider loadProvider() { try { Properties properties = new Properties(); properties.load(getClass().getResourceAsStream("/defaults.properties")); <START> Class<?> providerClass = Class.forName(properties.getProperty("provider")); <END> Constructor<?> constructor = providerClass.getConstructor(); return (Provider) constructor.newInstance(); } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }</code><technical_language>Return provider object new instead of Class.forName(...) provider module</technical_language>

Target:
protected Provider loadProvider() { try { return new GerritProvider(); } catch (Exception e) { throw new RuntimeException("could not create provider", e); } }
Source:
<code>public List<Role> getRoles(String inode, int permissionType, String filter, int start, int limit) { Inode inodeObj = null; List<Role> roleList = null; List<Permission> permissionList = null; try { Logger.debug( PermissionAPI.class, String.format("::getRoles -> before loading inode object(%s)", inode) ); Optional<ShortyId> shortOpt = APILocator.getShortyAPI().getShorty(inode); <START> if ( ShortType.STRUCTURE == shortOpt.get().subType ) { <END> ContentType foundContentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(inode); if ( null != foundContentType ) { inodeObj = new StructureTransformer(foundContentType).asStructure(); } } else { inodeObj = InodeFactory.getInode(inode, Inode.class); } permissionList = getPermissions(inodeObj, true); roleList = loadRolesForPermission(permissionList, permissionType, filter); if( start < roleList.size() ) { if (limit > -1 && start + limit < roleList.size() ) { roleList = roleList.subList(start, start + limit); } else { roleList = roleList.subList(start, roleList.size()); } } } catch (Exception e) { Logger.error(this,e.getMessage(),e); } finally { if( roleList == null ) { roleList = new ArrayList<Role>(0); } } return roleList; }</code><technical_language>This is important</technical_language>

Target:
public List<Role> getRoles(String inode, int permissionType, String filter, int start, int limit) { Inode inodeObj = null; List<Role> roleList = null; List<Permission> permissionList = null; try { Logger.debug( PermissionAPI.class, String.format("::getRoles -> before loading inode object(%s)", inode) ); Optional<ShortyId> shortOpt = APILocator.getShortyAPI().getShorty(inode); if ( shortOpt.isPresent() && ShortType.STRUCTURE == shortOpt.get().subType ) { ContentType foundContentType = APILocator.getContentTypeAPI(APILocator.systemUser()).find(inode); if ( null != foundContentType ) { inodeObj = new StructureTransformer(foundContentType).asStructure(); } } else { inodeObj = InodeFactory.getInode(inode, Inode.class); } permissionList = getPermissions(inodeObj, true); roleList = loadRolesForPermission(permissionList, permissionType, filter); if( start < roleList.size() ) { if (limit > -1 && start + limit < roleList.size() ) { roleList = roleList.subList(start, start + limit); } else { roleList = roleList.subList(start, roleList.size()); } } } catch (Exception e) { Logger.error(this,e.getMessage(),e); } finally { if( roleList == null ) { roleList = new ArrayList<Role>(0); } } return roleList; }
Source:
<code>private Object invokeMethod(String type, Method method, Object o, Object... args) { try { return method.invoke(o, args); } catch (InvocationTargetException e) { if (e.getTargetException() instanceof WebApplicationException) { return ((WebApplicationException) e.getTargetException()).getResponse(); } if (type.equals(COMPENSATE)) { <START> return ParticipantStatus.FailedToCompensate.name(); <END> } else if (type.equals(COMPLETE)) { return ParticipantStatus.FailedToComplete.name(); } else { return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build(); } } catch (IllegalAccessException e) { throw new RuntimeException(e); } }</code><technical_language>this is running in applications JVM logging condition</technical_language>

Target:
private Object invokeMethod(String type, Method method, Object o, Object... args) { try { return method.invoke(o, args); } catch (InvocationTargetException e) { return processThrowable(e.getTargetException(), type); } catch (IllegalAccessException e) { throw new RuntimeException(e); } }
Source:
<code>public void configureConfigSubmitAllowedWithSystemReadAndManagePermission() throws Exception { HtmlPage configure = webClient.login(SYSTEM_READER) .goTo("configure"); assertThat(configure.getWebResponse().getStatusCode(), is(200)); HtmlForm configureForm = configure.getFormByName("config"); <START> HtmlPage submit = j.submit(configureForm); <END> assertThat(submit.getWebResponse().getStatusCode(), is(200)); }</code><technical_language>get a test ensures non-editable fields remain (e.g. master executors), manipulated form submissions effective. Basically, test Unclassified/ UnclassifiedReadable separation. easiest a test-only descriptor global.jelly bypasses read-only mode, sets non-default Jelly/Groovy view, messing UI in HTMLUnit is needed</technical_language>

Target:
public void configureConfigSubmitAllowedWithSystemReadAndManagePermission() throws Exception { HtmlPage configure = webClient.login(SYSTEM_READER_AND_MANAGER) .goTo("configure"); assertThat(configure.getWebResponse().getStatusCode(), is(200)); HtmlForm configureForm = configure.getFormByName("config"); HtmlPage submit = j.submit(configureForm); assertThat(submit.getWebResponse().getStatusCode(), is(200)); }
Source:
<code>public Organization getOrganizationByName(String name) { ValidateArgument.required(name, "name"); try { DBOOrganization dbo = jdbcTemplate.queryForObject( "SELECT * FROM " + TABLE_ORGANIZATION + " WHERE " + COL_ORGANIZATION_NAME + " = ?", ROW_MAPPER, name.toLowerCase()); return createDtoFromDbo(dbo); } catch (EmptyResultDataAccessException e) { <START> throw new NotFoundException("Orgnaization with name: '" + name.toLowerCase() + "' not found"); <END> } }</code><technical_language>Typo: Organization</technical_language>

Target:
public Organization getOrganizationByName(String name) { ValidateArgument.required(name, "name"); try { DBOOrganization dbo = jdbcTemplate.queryForObject( "SELECT * FROM " + TABLE_ORGANIZATION + " WHERE " + COL_ORGANIZATION_NAME + " = ?", ROW_MAPPER, name.toLowerCase()); return createDtoFromDbo(dbo); } catch (EmptyResultDataAccessException e) { throw new NotFoundException("Organization with name: '" + name.toLowerCase() + "' not found"); } }
Source:
<code><START> public static Map<String, List<String>> getRawRoutingData() <END> throws IOException { if (_rawRoutingData == null) { synchronized (HttpRoutingDataReader.class) { if (_rawRoutingData == null) { String msdsEndpoint = System.getProperty(MetadataStoreRoutingConstants.MSDS_SERVER_ENDPOINT_KEY); if (msdsEndpoint == null || msdsEndpoint.isEmpty()) { throw new IllegalStateException( "HttpRoutingDataReader was unable to find a valid MSDS endpoint String in System Properties!"); } CloseableHttpClient httpClient = HttpClients.createDefault(); _rawRoutingData = getAllRoutingData(httpClient, msdsEndpoint); httpClient.close(); } } } return _rawRoutingData; }</code><technical_language>this is a public API? Do intend provide this users? Is a case</technical_language>

Target:
public static Map<String, List<String>> getRawRoutingData() throws IOException { if (MSDS_ENDPOINT == null || MSDS_ENDPOINT.isEmpty()) { throw new IllegalStateException( "HttpRoutingDataReader was unable to find a valid MSDS endpoint String in System Properties!"); } if (_rawRoutingData == null) { synchronized (HttpRoutingDataReader.class) { if (_rawRoutingData == null) { String routingDataJson = getAllRoutingData(); _rawRoutingData = parseRoutingData(routingDataJson); } } } return _rawRoutingData; }
Source:
<code>public String addGateway(AuthzToken authzToken, Gateway gateway) throws TenantProfileServiceException, AuthorizationException, TException { try { <START> if (!checkDuplicate(gateway)) { <END> gateway = tenantProfileRepository.create(gateway); } if (gateway != null) { logger.info("Added Airavata Gateway with Id: " + gateway.getGatewayId()); if (gateway.getGatewayApprovalStatus().equals(GatewayApprovalStatus.APPROVED)) { logger.info("Gateway with ID: {}, is now APPROVED, replicating to subscribers.", gateway.getGatewayId()); ProfileServiceUtils.getDbEventPublisher().publish( ProfileServiceUtils.getDBEventMessageContext(EntityType.TENANT, CrudType.CREATE, gateway), DBEventManagerConstants.getRoutingKey(DBEventService.DB_EVENT.toString()) ); } return gateway.getGatewayId(); } else { throw new Exception("Gateway object is null."); } } catch (Exception ex) { logger.error("Error adding gateway-profile, reason: " + ex.getMessage(), ex); TenantProfileServiceException exception = new TenantProfileServiceException(); exception.setMessage("Error adding gateway-profile, reason: " + ex.getMessage()); throw exception; } }</code><technical_language>If is a duplicate I code throw a TenantProfileServiceException error message explaining is a duplicate</technical_language>

Target:
public String addGateway(AuthzToken authzToken, Gateway gateway) throws TenantProfileServiceException, AuthorizationException, TException { try { if (!checkDuplicateGateway(gateway)) { gateway = tenantProfileRepository.create(gateway); if (gateway != null) { logger.info("Added Airavata Gateway with Id: " + gateway.getGatewayId()); if (gateway.getGatewayApprovalStatus().equals(GatewayApprovalStatus.APPROVED)) { logger.info("Gateway with ID: {}, is now APPROVED, replicating to subscribers.", gateway.getGatewayId()); ProfileServiceUtils.getDbEventPublisher().publish( ProfileServiceUtils.getDBEventMessageContext(EntityType.TENANT, CrudType.CREATE, gateway), DBEventManagerConstants.getRoutingKey(DBEventService.DB_EVENT.toString()) ); } return gateway.getGatewayId(); } else { throw new Exception("Gateway object is null."); } } else { throw new TenantProfileServiceException("An approved Gateway already exists with the same GatewayId, Name or URL"); } } catch (Exception ex) { logger.error("Error adding gateway-profile, reason: " + ex.getMessage(), ex); TenantProfileServiceException exception = new TenantProfileServiceException(); exception.setMessage("Error adding gateway-profile, reason: " + ex.getMessage()); throw exception; } }
Source:
<code>public void receiveResponse(Exchange exchange, Response response) { Request request = exchange.getCurrentRequest(); if(!isProtected(response)) { <START> LOGGER.warn("Incoming response is NOT OSCORE protected!"); <END> } else { LOGGER.info("Incoming response is OSCORE protected"); } if (request == null) { LOGGER.error("No request tied to this response"); return; } try { if (isProtected(response)) { response = prepareReceive(response); } } catch (OSException e) { LOGGER.error("Error while receiving OSCore response: " + e.getMessage()); EmptyMessage error = CoapOSExceptionHandler.manageError(e, response); if (error != null) { sendEmptyMessage(exchange, error); } return; } super.receiveResponse(exchange, response); }</code><technical_language>"warn" only, if request OSCORE</technical_language>

Target:
public void receiveResponse(Exchange exchange, Response response) { Request request = exchange.getCurrentRequest(); if (request == null) { LOGGER.error("No request tied to this response"); return; } try { if (!isProtected(response) && responseShouldBeProtected(exchange, response)) { LOGGER.warn("Incoming response is NOT OSCORE protected!"); } else if (isProtected(response)) { LOGGER.info("Incoming response is OSCORE protected"); } if (isProtected(response)) { response = prepareReceive(response); } } catch (OSException e) { LOGGER.error("Error while receiving OSCore response: " + e.getMessage()); EmptyMessage error = CoapOSExceptionHandler.manageError(e, response); if (error != null) { sendEmptyMessage(exchange, error); } return; } super.receiveResponse(exchange, response); }
Source:
<code>public final void create() { if (CLEAR_SETTINGS) { Preferences preferences = Gdx.app.getPreferences("TIMER"); preferences.clear(); preferences.flush(); } Gdx.app.setLogLevel(Application.LOG_DEBUG); cTimeKeeper = TimerStore.getInstance().getTimeKeeper(); cStandUp = StandUp.getInstance(); Collection c = new Collection(); c.add(new FishA(780)); c.add(new FishB(580)); c.add(new FishC(380)); ScreenStore cScreenStore = ScreenStore.getInstance(); setScreen(cScreenStore.getWorldRenderer()); <START> cScreenStore.init(c); <END> cScreenStore.setScreen("Home"); }</code><technical_language>A screenstore need a collection.. creation of a collectible screen retrieve players collection. subscribe something.</technical_language>

Target:
public final void create() { if (CLEAR_SETTINGS) { Preferences preferences = Gdx.app.getPreferences("TIMER"); preferences.clear(); preferences.flush(); } Gdx.app.setLogLevel(Application.LOG_DEBUG); cTimeKeeper = TimerStore.getInstance().getTimeKeeper(); cStandUp = StandUp.getInstance(); int fa = 0, fb = 0, fc = 0; Collection c = new Collection("local"); RewardGenerator gen = new RewardGenerator(); for(int i = 0; i < 500; i++) { Collectible ca = gen.generateCollectible(1); c.add(ca); if(ca instanceof FishA) { fa++; } else if (ca instanceof FishB) { fb++; } else { fc++; } } System.out.println("Fish A: " + fa + " Fish B: " + fb + " Fish C: " + fc); ScreenStore cScreenStore = ScreenStore.getInstance(); setScreen(cScreenStore.getWorldRenderer()); cScreenStore.init(c); cScreenStore.setScreen("Home"); }
Source:
<code>public void handle(RMNode node) { <START> if (!initialized || node.isLocked() || isRestorationCompleted()) { <END> if (log.isDebugEnabled()) { String nodeUrl = node.getNodeURL(); if (!initialized) { logSkipReason(nodeUrl, "manager is not yet initialized"); } else if (node.isLocked()) { logSkipReason(nodeUrl, "it is locked"); } else { logSkipReason(nodeUrl, "restoration is complete"); } } return; } String nodeSource = node.getNodeSourceName(); MutableInteger nodeCount = nodeLockedOnPreviousRun.get(nodeSource); if (nodeCount != null) { lockNode(node); if (nodeCount.add(-1) == 0) { nodeLockedOnPreviousRun.remove(nodeSource); } } }</code><technical_language>wrap this validation a private method called boolean isNodeValidToBeRestored(RMNode node) that</technical_language>

Target:
public void handle(RMNode node) { if (!isNodeValidToBeRestored(node)) { if (log.isDebugEnabled()) { String nodeUrl = node.getNodeURL(); if (!initialized) { logSkipReason(nodeUrl, "manager is not yet initialized"); } else if (node.isLocked()) { logSkipReason(nodeUrl, "it is locked"); } else { logSkipReason(nodeUrl, "restoration is complete"); } } return; } String nodeSource = node.getNodeSourceName(); MutableInteger nodeCount = nodeLockedOnPreviousRun.get(nodeSource); if (nodeCount != null) { lockNode(node); int newNodeCount = nodeCount.add(-1); if (newNodeCount == 0) { nodeLockedOnPreviousRun.remove(nodeSource); } } }
Source:
<code>public void start(final BundleContext context) throws Exception { super.start(context); Dictionary<String, String> props = new Hashtable<String, String>(4); props.put(DebugOptions.LISTENER_SYMBOLICNAME, context.getBundle() .getSymbolicName()); context.registerService(DebugOptionsListener.class.getName(), this, props); setupSSH(context); setupProxy(context); setupRepoChangeScanner(); setupRepoIndexRefresh(); <START> if (PlatformUI.isWorkbenchRunning()) <END> setupFocusHandling(); setupCredentialsProvider(); ConfigurationChecker.checkConfiguration(); }</code><technical_language>explanation nice</technical_language>

Target:
public void start(final BundleContext context) throws Exception { super.start(context); Dictionary<String, String> props = new Hashtable<String, String>(4); props.put(DebugOptions.LISTENER_SYMBOLICNAME, context.getBundle() .getSymbolicName()); context.registerService(DebugOptionsListener.class.getName(), this, props); setupSSH(context); setupProxy(context); setupRepoChangeScanner(); setupRepoIndexRefresh(); setupFocusHandling(); setupCredentialsProvider(); ConfigurationChecker.checkConfiguration(); }
Source:
<code>public final Set<SequenceSegment> getVisibleSegments(final int position) { Set<SequenceSegment> copy = new TreeSet<SequenceSegment>(); <START> try { <END> for (SequenceSegment seg : segmentBuckets.getSegments(position)) { copy.add(seg.clone()); } } catch (CloneNotSupportedException e) { Logging.exception(e); } copy.retainAll(visibles); if (visibleSequences != null) { for (SequenceSegment vertex : copy) { vertex.getSources().retainAll(visibleSequences); } } return copy; }</code><technical_language>try ... catch-block loop debugged more easily</technical_language>

Target:
public final Set<SequenceSegment> getVisibleSegments(final int position) { Set<SequenceSegment> copy = new TreeSet<SequenceSegment>(); for (SequenceSegment seg : segmentBuckets.getSegments(position)) { try { copy.add(seg.clone()); } catch (CloneNotSupportedException e) { Logging.exception(e); } } copy.retainAll(visibles); if (visibleSequences != null) { for (SequenceSegment vertex : copy) { vertex.getSources().retainAll(visibleSequences); } } return copy; }
Source:
<code>private ModelAndView redirectToAssetFile(HttpServletRequest request, Site site, String id, String fileType, boolean isDownload) { Link.Factory.PatternBuilder link = Link.toLocalSite(site) .toPattern(requestMappingContextDictionary, "assetFile") .addQueryParameter("id", id) .addQueryParameter("type", fileType); if (isDownload) { link = link.addQueryParameter("download", ""); } <START> RedirectView redirectView = new RedirectView(link.build().getRedirect(request)); <END> redirectView.setStatusCode(HttpStatus.MOVED_PERMANENTLY); return new ModelAndView(redirectView); }</code><technical_language>this opportunity Link.getRedirect construct return RedirectView instead of a String? I returning a bare string "redirect:" appended it</technical_language>

Target:
private ModelAndView redirectToAssetFile(HttpServletRequest request, Site site, String id, String fileType, boolean isDownload) { Link.Factory.PatternBuilder link = Link.toLocalSite(site) .toPattern(requestMappingContextDictionary, "assetFile") .addQueryParameter("id", id) .addQueryParameter("type", fileType); if (isDownload) { link = link.addQueryParameter("download", ""); } return new ModelAndView(link.build().getRedirect(request)); }
Source:
<code>public void setUp() throws Exception { DbFacadeLocator.setDbFacade(dbFacade); when(dbFacade.getStoragePoolDao()).thenReturn(storagePoolDao); when(dbFacade.getVmNicDao()).thenReturn(vmNicDao); when(dbFacade.getMacPoolDao()).thenReturn(macPoolDao); macFrom = "00:1a:4a:15:c0:00"; <START> macTo = "00:1a:4a:15:c0:ff"; <END> macPool = createMacPool(macFrom, macTo); dataCenter = createStoragePool(macPool); vmNic = createVmNic(); }</code><technical_language>constants converted constants.</technical_language>

Target:
public void setUp() throws Exception { DbFacadeLocator.setDbFacade(dbFacade); when(dbFacade.getStoragePoolDao()).thenReturn(storagePoolDao); when(dbFacade.getVmNicDao()).thenReturn(vmNicDao); when(dbFacade.getMacPoolDao()).thenReturn(macPoolDao); when(dbFacade.getAuditLogDao()).thenReturn(auditLogDao); macPool = createMacPool(MAC_FROM, MAC_TO); dataCenter = createStoragePool(macPool); vmNic = createVmNic(); pool = new MacPoolPerDc(); }
Source:
<code>public void init(HttpServletRequest request, HttpServletResponse response) { RequestData data = monitor.current(); if (data == null) { return; } data.setCategory(Category.REST); if (request.getPathInfo() != null) { <START> try { <END> String resource = Paths.get(URLEncoder.encode(request.getPathInfo(), Charset.defaultCharset().name())).getFileName().toString(); resource = FilenameUtils.getBaseName(resource); data.getResources().add(resource); } catch (UnsupportedEncodingException e) { LOGGER.log(Level.SEVERE, e.getMessage(), e); } } monitor.update(); }</code><technical_language>Needs a test (like other bug fix)</technical_language>

Target:
public void init(HttpServletRequest request, HttpServletResponse response) { RequestData data = monitor.current(); if (data == null) { return; } data.setCategory(Category.REST); if (request.getPathInfo() != null) { String resource = request.getPathInfo(); final String[] pathParts = resource.split("/"); data.getResources().add(pathParts[pathParts.length - 1]); } monitor.update(); }
Source:
<code>private long findUnusedMac() { int index = usedMacs.nextClearBit(startingLocationWhenSearchingForUnusedMac); boolean notFound = index == numberOfMacsInRange; if (notFound) { index = usedMacs.nextClearBit(0); } <START> startingLocationWhenSearchingForUnusedMac = index + 1; <END> return rangeStart + index; }</code><technical_language>be- (index +1) % numberOfMacsInRange</technical_language>

Target:
private long findUnusedMac() { int index = usedMacs.nextClearBit(startingLocationWhenSearchingForUnusedMac); boolean notFound = index == numberOfMacsInRange; if (notFound) { index = usedMacs.nextClearBit(0); } startingLocationWhenSearchingForUnusedMac = (index + 1) % numberOfMacsInRange; return rangeStart + index; }
Source:
<code>public void testToJsonOnClass() throws IOException { checkToJson(new Function<Statistics, String>() { @Override public String apply(Statistics t) { try { return Statistics.toJson(t); } catch (JsonProcessingException e) { <START> e.printStackTrace(); <END> } return null; } }); }</code><technical_language>assert fail</technical_language>

Target:
public void testToJsonOnClass() throws IOException { checkToJson(new Function<Statistics, String>() { @Override public String apply(Statistics t) { try { return Statistics.toJson(t); } catch (JsonProcessingException e) { Assert.fail(e.toString()); } return null; } }); }
Source:
<code>private static Number evaluateBinding(IBinding b) { if (b instanceof IType) { return VALUE_CANNOT_BE_DETERMINED; } if (b instanceof ICPPTemplateNonTypeParameter) { return null; } if (b instanceof ICPPUnknownBinding) { return null; } IValue value= null; if (b instanceof IVariable) { <START> IVariable bVar = (IVariable) b; <END> IType realType = SemanticUtil.getNestedType(bVar.getType(), SemanticUtil.TDEF); if (realType instanceof IQualifierType) { if (((IQualifierType)realType).isConst()) { value= ((IVariable) b).getInitialValue(); } } } else if (b instanceof IEnumerator) { value= ((IEnumerator) b).getValue(); } if (value != null && value != Value.UNKNOWN) { return value.numericalValue(); } return VALUE_CANNOT_BE_DETERMINED; }</code><technical_language>This changed. Evaluating code figure out this is applicable not. For example in initiazer this is const not. data-flow fail</technical_language>

Target:
private static Number evaluateBinding(IBinding b) { if (b instanceof IType) { return VALUE_CANNOT_BE_DETERMINED; } if (b instanceof ICPPTemplateNonTypeParameter) { return null; } if (b instanceof ICPPUnknownBinding) { return null; } IValue value= null; if (b instanceof IVariable) { value= ((IVariable) b).getInitialValue(); } else if (b instanceof IEnumerator) { value= ((IEnumerator) b).getValue(); } if (value != null && value != Value.UNKNOWN) { return value.numericalValue(); } return VALUE_CANNOT_BE_DETERMINED; }
Source:
<code>private JSONObject getJsonFromUri(final String path) throws IOException, JSONException { try { <START> URI pathUi = new URI(null, null, path, null); <END> URL url = new URL(this.remoteAssetsConfig.getServer() + pathUi.toString() + ".1.json"); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestProperty("Authorization", String.format("Basic %s", RemoteAssets.encodeForBasicAuth(this.remoteAssetsConfig))); try (BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { String line; StringBuilder sb = new StringBuilder(); while ((line = br.readLine()) != null) { sb.append(line); } String sbString = sb.toString(); if (StringUtils.startsWith(sbString, "{")) { if (LOG.isDebugEnabled()) { LOG.debug("JSON successfully fetched for URL '{}'.", url.toString()); } return new JSONObject(sbString); } else { LOG.error("Unable to grab JSON Object. Please ensure URL is valid. \nRaw Response: {}", url.toString(), sbString); } } finally { connection.disconnect(); } } catch (URISyntaxException e) { LOG.error("URI Syntax Exception {}", e); } throw new JSONException("Response JSON came back null."); }</code><technical_language>typo in pathUi (pathUri)</technical_language>

Target:
private JsonObject getJsonFromUri(final String path) throws IOException { URI pathUri; try { pathUri = new URI(null, null, path, null); } catch (URISyntaxException e) { LOG.error("URI Syntax Exception", e); throw new IOException("Invalid URI", e); } String url = this.remoteAssetsConfig.getServer() + pathUri.toString() + ".1.json"; Executor executor = this.remoteAssetsConfig.getRemoteAssetsHttpExecutor(); String responseString = executor.execute(Request.Get(url)).returnContent().asString(); try { JsonObject responseJson = new JsonParser().parse(responseString).getAsJsonObject(); LOG.debug("JSON successfully fetched for URL '{}'.", url); return responseJson; } catch (JsonSyntaxException | IllegalStateException e) { LOG.error("Unable to grab JSON Object. Please ensure URL is valid. \nRaw Response: {}", url, responseString); throw new IOException("Invalid JSON response", e); } }
Source:
<code>public void testDeleteJobs() throws Exception { <START> JobsList.listJobs(PROJECT_ID); <END> String output = bout.toString(); Matcher matcher = JOB_ID_PATTERN.matcher(bout.toString()); assertTrue("List must contain results.", matcher.find()); String jobId = matcher.group(0).split("/")[3]; bout.reset(); JobsDelete.deleteJobs(PROJECT_ID, jobId); output = bout.toString(); assertTrue(output.contains("Job deleted successfully.")); }</code><technical_language>create a short script show issue open issue repo contains it</technical_language>

Target:
public void testDeleteJobs() throws Exception { String jobId = UUID.randomUUID().toString(); createJob(jobId); JobsDelete.deleteJobs(PROJECT_ID, "i-" + jobId); String output = bout.toString(); assertThat(output, CoreMatchers.containsString("Job deleted successfully.")); }
Source:
<code>private static List<VmDevice> sortInterfacesByName(VM vm, List<VmDevice> pluggedInterfaces) { if (pluggedInterfaces.size() < 2) { return pluggedInterfaces; } <START> final HashMap<Guid, String> deviceIdToIfaceName = new HashMap<Guid, String>(); <END> for (VmNetworkInterface iface : vm.getInterfaces()) { deviceIdToIfaceName.put(iface.getId(), iface.getName()); } Collections.sort(pluggedInterfaces, new Comparator<VmDevice>() { @Override public int compare(VmDevice first, VmDevice second) { Guid firstDeviceId = first.getId().getDeviceId(); Guid secondDeviceId = second.getId().getDeviceId(); String firstIfaceName = deviceIdToIfaceName.get(firstDeviceId); String secondIfaceName = deviceIdToIfaceName.get(secondDeviceId); return firstIfaceName.compareTo(secondIfaceName); } }); return pluggedInterfaces; }</code><technical_language>Reference type Map</technical_language>

Target:
private static List<VmDevice> sortInterfacesByName(VM vm, List<VmDevice> pluggedInterfaces) { if (pluggedInterfaces.size() < 2) { return pluggedInterfaces; } final Map<Guid, String> deviceIdToIfaceName = new HashMap<Guid, String>(); for (VmNetworkInterface iface : vm.getInterfaces()) { deviceIdToIfaceName.put(iface.getId(), iface.getName()); } Collections.sort(pluggedInterfaces, new Comparator<VmDevice>() { @Override public int compare(VmDevice first, VmDevice second) { Guid firstDeviceId = first.getId().getDeviceId(); Guid secondDeviceId = second.getId().getDeviceId(); String firstIfaceName = deviceIdToIfaceName.get(firstDeviceId); String secondIfaceName = deviceIdToIfaceName.get(secondDeviceId); return firstIfaceName.compareTo(secondIfaceName); } }); return pluggedInterfaces; }
Source:
<code><START> protected boolean validate() { <END> if (getVds() == null && !selectProxyHost()) { return failValidation(EngineMessage.ACTION_TYPE_FAILED_NO_VDS_IN_POOL); } return true; }</code><technical_language>I status of VM image status checked</technical_language>

Target:
protected boolean validate() { DiskValidator diskValidator = new DiskValidator(getDiskImage(), vmDeviceUtils); if (!validate(diskValidator.isDiskExists()) || !validate(diskValidator.isDiskPluggedToVmsThatAreNotDown(false, vmsForDisk))) { return false; } DiskImagesValidator diskImagesValidator = new DiskImagesValidator(Collections.singletonList(getDiskImage())); return validate(diskImagesValidator.diskImagesNotIllegal()) && validate(diskImagesValidator.diskImagesNotLocked()) && validate(diskImagesValidator.diskImagesHaveNoDerivedDisks(null)); }
Source:
<code>public static boolean deleteRealm(String canonicalPath, File realmFolder, String realmFileName) { final String management = ".management"; File managementFolder = new File(realmFolder, realmFileName + management); File realmFile = new File(canonicalPath); File[] files = managementFolder.listFiles(); if (files != null) { for (File file : files) { boolean deleteResult = file.delete(); if (!deleteResult) { <START> RealmLog.warn( String.format(Locale.ENGLISH,"Realm temporary file at %s cannot deleted", <END> file.getAbsolutePath())); } } } if (managementFolder.exists() && !managementFolder.delete()) { RealmLog.warn( String.format(Locale.ENGLISH,"Realm temporary folder at %s cannot deleted", managementFolder.getAbsolutePath())); } boolean realmDeleted; if (realmFile.exists()) { realmDeleted = realmFile.delete(); if (!realmDeleted) { RealmLog.warn( String.format(Locale.ENGLISH,"Realm file at %s cannot deleted", realmFile.getAbsolutePath())); } } else { realmDeleted = true; } return realmDeleted; }</code><technical_language>deleted</technical_language>

Target:
public static boolean deleteRealm(String canonicalPath, File realmFolder, String realmFileName) { final String management = ".management"; File managementFolder = new File(realmFolder, realmFileName + management); File realmFile = new File(canonicalPath); File[] files = managementFolder.listFiles(); if (files != null) { for (File file : files) { boolean deleteResult = file.delete(); if (!deleteResult) { RealmLog.warn( String.format(Locale.ENGLISH,"Realm temporary file at %s cannot be deleted", file.getAbsolutePath())); } } } if (managementFolder.exists() && !managementFolder.delete()) { RealmLog.warn( String.format(Locale.ENGLISH,"Realm temporary folder at %s cannot be deleted", managementFolder.getAbsolutePath())); } boolean realmDeleted; if (realmFile.exists()) { realmDeleted = realmFile.delete(); if (!realmDeleted) { RealmLog.warn(String.format(Locale.ENGLISH,"Realm file at %s cannot be deleted", realmFile.getAbsolutePath())); } } else { realmDeleted = true; } return realmDeleted; }
Source:
<code>public static ArrayPool<boolean[]> getBooleanArrayPool() { synchronized (Caches.class) { if (booleanArrayPool == null) { booleanArrayPool = new ArrayPool(16, 64 * 1024, 1024 * 1024, new BooleanArrayAllocator()); } } return booleanArrayPool; <START> } <END></code><technical_language>move this member variable next other variables</technical_language>

Target:
public static ArrayPool<boolean[]> getBooleanArrayPool() { synchronized (Caches.class) { if (booleanArrayPool == null) { booleanArrayPool = new ArrayPool(BOOLEAN_SMALLEST_ARRAY_SIZE, BOOLEAN_LARGEST_ARRAY_SIZE, BOOLEAN_POOL_CAPACITY, new BooleanArrayAllocator()); } } return booleanArrayPool; }
Source:
<code>void onSaveProfileClicked() { Timber.v("Attempting to save profile"); String firstName = firstNameEditText.getText().toString(); String lastName = lastNameEditText.getText().toString(); UserSpec spec = new UserSpec(); User user = new User(); user.getData().attributes().firstName(firstName); user.getData().attributes().lastName(lastName); spec.create(new CreateUserRequest()); spec.update(user); userRepo.update(spec) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted( new Action0() { @Override public void call() { Timber.v("Profile saved"); ToastService.get(getView()).bern(getView().getContext().getString(R.string.profile_saved)); Flow.get(getView().getContext()).set(new HomeScreen()); } } ) .doOnError( new Action1<Throwable>() { @Override public void call(Throwable throwable) { <START> Timber.e("Unable to save profile", throwable); <END> ToastService.get(getView()).bern(getView().getContext().getString(R.string.error_saving_profile)); } } ) .subscribe(); }</code><technical_language>Is this right argument order? worth a Bugsnag.notify(throwable)</technical_language>

Target:
void onSaveProfileClicked() { Timber.v("Attempting to save profile"); String firstName = firstNameEditText.getText().toString(); String lastName = lastNameEditText.getText().toString(); UserSpec spec = new UserSpec(); User user = new User(); user.getData().attributes().firstName(firstName); user.getData().attributes().lastName(lastName); spec.create(new CreateUserRequest()); spec.update(user); userRepo.update(spec) .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .doOnCompleted( new Action0() { @Override public void call() { Timber.v("Profile saved"); ProfileView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.profile_saved)); Flow.get(view.getContext()).set(new HomeScreen()); } else { Timber.w("getView() null, cannot notify user of successful profile save"); } } } ) .doOnError( new Action1<Throwable>() { @Override public void call(Throwable throwable) { Timber.e(throwable, "Unable to save profile"); Bugsnag.notify(throwable); ProfileView view = getView(); if (view != null) { ToastService.get(view).bern(view.getContext().getString(R.string.error_saving_profile)); } else { Timber.w("getView() null, cannot notify user of failed profile save"); } } } ) .subscribe(); }
Source:
<code>protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, final SourceUnit sourceUnit) { final ClassLoader classLoader = this.getClass().getClassLoader(); return new ClassCodeVisitorSupport() { @Override protected SourceUnit getSourceUnit() { return sourceUnit; } @Override <START> public void visitMethodCallExpression(MethodCallExpression call) { <END> super.visitMethodCallExpression(call); List<MethodNode> methods = MacroMethodsCache.get(classLoader).get(call.getMethodAsString()); if (methods == null) { return; } List<Expression> callArguments = InvocationWriter.makeArgumentList(call.getArguments()).getExpressions(); ClassNode[] argumentsList = new ClassNode[callArguments.size()]; for (int i = 0; i < callArguments.size(); i++) { argumentsList[i] = ClassHelper.make(callArguments.get(i).getClass()); } methods = StaticTypeCheckingSupport.chooseBestMethod(MACRO_CONTEXT_CLASS_NODE, methods, argumentsList); for (MethodNode macroMethodNode : methods) { if (!(macroMethodNode instanceof ExtensionMethodNode)) { continue; } MethodNode macroExtensionMethodNode = ((ExtensionMethodNode) macroMethodNode).getExtensionMethodNode(); final Class clazz; try { clazz = classLoader.loadClass(macroExtensionMethodNode.getDeclaringClass().getName()); } catch (ClassNotFoundException e) { continue; } MacroContext macroContext = new MacroContext(unit, sourceUnit, call); List<Object> macroArguments = new ArrayList<>(); macroArguments.add(macroContext); macroArguments.addAll(callArguments); Expression result = (Expression) InvokerHelper.invokeStaticMethod(clazz, macroMethodNode.getName(), macroArguments.toArray()); call.setObjectExpression(MACRO_STUB_INSTANCE); call.setMethod(new ConstantExpression(MACRO_STUB_METHOD_NAME)); call.setSpreadSafe(false); call.setSafe(false); call.setImplicitThis(false); call.setArguments(result); break; } } }; }</code><technical_language>This method is long. split smaller focused pieces</technical_language>

Target:
protected GroovyCodeVisitor getTransformer(ASTNode[] nodes, final SourceUnit sourceUnit) { return new MacroCallTransformingVisitor(sourceUnit, unit); }
Source:
<code>public Optional get(final J2EContext context, final String key) { <START> return Optional.of(getHttpSession(context).getAttribute(key)); <END> }</code><technical_language>OfNullable I suppose</technical_language>

Target:
public Optional get(final J2EContext context, final String key) { return Optional.ofNullable(getHttpSession(context).getAttribute(key)); }
Source:
<code>public static int getOffsetForCursorLocation(ITextViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) return -1; Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); int <START> widgetOffset= text.getOffsetAtPoint(relativePosition); <END> Point p= text.getLocationAtOffset(widgetOffset); if (p.x > relativePosition.x) widgetOffset--; if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5)viewer; return extension.widgetOffset2ModelOffset(widgetOffset); } return widgetOffset + viewer.getVisibleRegion().getOffset(); } catch (IllegalArgumentException e) { return -1; } }</code><technical_language>this continue if (widgetOffset == -1) { return -1; }</technical_language>

Target:
public static int getOffsetForCursorLocation(ITextViewer viewer) { try { StyledText text= viewer.getTextWidget(); if (text == null || text.isDisposed()) { return -1; } Display display= text.getDisplay(); Point absolutePosition= display.getCursorLocation(); Point relativePosition= text.toControl(absolutePosition); int widgetOffset= text.getOffsetAtPoint(relativePosition); if (widgetOffset == -1) { return -1; } Point p= text.getLocationAtOffset(widgetOffset); if (p.x > relativePosition.x) { widgetOffset--; } if (viewer instanceof ITextViewerExtension5) { ITextViewerExtension5 extension= (ITextViewerExtension5)viewer; return extension.widgetOffset2ModelOffset(widgetOffset); } return widgetOffset + viewer.getVisibleRegion().getOffset(); } catch (IllegalArgumentException e) { return -1; } }