auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public static <T extends TimeValue> T positive(final T timeValue, final String name) { <START> positive(timeValue.toMilliseconds(), name); <END> return timeValue; }</code><technical_language>This dangerous if supplies microsecond resolution 0 ms, trigger exception. getDuration()</technical_language>

Target:
public static <T extends TimeValue> T positive(final T timeValue, final String name) { positive(timeValue.getDuration(), name); return timeValue; }
Source:
<code>public void run() { if (!this.getBuilder().getJob().isBuildable()) { logger.info(format("Build Skip (%s).", getBuilder().getJob().getName())); } else if(checkAlreadyQueued.compareAndSet(false, true)) { logger.info(format("Build started (%s).", getBuilder().getJob().getName())); descriptor.getExecutorService().execute(new Runnable() { @Override public void run() { try { <START> stashPullRequestsBuilder.run(); <END> } finally { checkAlreadyQueued.set(false); } } }); } else { logger.info(format("Build check already queued - skipping (%s).", getBuilder().getJob().getName())); } this.getDescriptor().save(); }</code><technical_language>Is intentention exceptions now</technical_language>

Target:
public void run() { if (!this.getBuilder().getJob().isBuildable()) { logger.info(format("Build Skip (%s).", getBuilder().getJob().getName())); } else if(checkAlreadyQueued.compareAndSet(false, true)) { logger.info(format("Build started (%s).", getBuilder().getJob().getName())); descriptor.getExecutorService().execute(new Runnable() { @Override public void run() { try { stashPullRequestsBuilder.run(); } catch (Exception e) { logger.log(Level.WARNING, "Stash Pull Request Builder failed when checking for changes", e); } finally { checkAlreadyQueued.set(false); } } }); } else { logger.info(format("Build check already queued - skipping (%s).", getBuilder().getJob().getName())); } this.getDescriptor().save(); }
Source:
<code>private void checkTableNotExists(SchemaTableName tableName) { if (tables.values().stream() .map(MemoryTableHandle::toSchemaTableName) .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString())); } <START> if (views.keySet().stream() <END> .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString())); } }</code><technical_language>Nit: I wrap here, short item, wrapping harder read</technical_language>

Target:
private void checkTableNotExists(SchemaTableName tableName) { if (tables.values().stream() .map(MemoryTableHandle::toSchemaTableName) .anyMatch(tableName::equals)) { throw new PrestoException(ALREADY_EXISTS, format("Table [%s] already exists", tableName.toString())); } if (views.keySet().contains(tableName)) { throw new PrestoException(ALREADY_EXISTS, format("View [%s] already exists", tableName.toString())); } }
Source:
<code>public void testRequireNull() { RequiredModel model = new RequiredModel(); model.field = null; <START> RequiredModel result = unmarshal(RequiredModel.class, marshal(model)); <END> assertThat(result, nullValue()); }</code><technical_language>Marshal serialize nulls default. write JSON hand ("{field: null}") call GsonBuilder.serializeNulls(). is currently written, testRequireNull() testRequireMissing() testing identical inputs</technical_language>

Target:
public void testRequireNull() { RequiredModel model = new RequiredModel(); RequiredModel result = unmarshal(gson, RequiredModel.class, marshal(gson, model)); assertThat(result, nullValue()); }
Source:
<code>public List<Action> getActions() { List<Action> actions = new ArrayList<>(); final Collection<? extends AbstractContent> selectedContents = Utilities.actionsGlobalContext().lookupAll(AbstractContent.class); <START> if (!selectedContents.isEmpty() && selectedContents.size() == 1) { <END> AbstractContent content = selectedContents.toArray(new AbstractContent[selectedContents.size()])[0]; try { if (content instanceof AbstractFile && content.getArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED).size() > 0 && DOCUMENT_EXTENSIONS.contains("." + ((AbstractFile) content).getNameExtension().toLowerCase())) { actions.add(new ExtractDocumentWithPasswordAction(((AbstractFile) content))); } } catch (TskCoreException | NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to add unzip with password action to context menus", ex); } } return actions; }</code><technical_language>need check for a size of 1</technical_language>

Target:
public List<Action> getActions() { List<Action> actions = new ArrayList<>(); final Collection<? extends AbstractFile> selectedContents = Utilities.actionsGlobalContext().lookupAll(AbstractFile.class); if (selectedContents.size() == 1) { AbstractFile content = selectedContents.toArray(new AbstractFile[selectedContents.size()])[0]; try { if (content.getArtifacts(BlackboardArtifact.ARTIFACT_TYPE.TSK_ENCRYPTION_DETECTED).size() > 0 && DOCUMENT_EXTENSIONS.contains(content.getNameExtension().toLowerCase())) { actions.add(new ExtractDocumentWithPasswordAction(content)); } } catch (TskCoreException | NoCurrentCaseException ex) { logger.log(Level.WARNING, "Unable to to add Extract Content with Password action to context menus", ex); } } return actions; }
Source:
<code>protected HttpClient getHttpClient(Integer readTimeout, Integer connectTimeout) { if (getDoCacheClient() && HTTP_CLIENT_API_43) { if (cachedClient == null) { cachedClient = getNewPooledHttpClient(readTimeout, connectTimeout); } return cachedClient; } if (HTTP_CLIENT_API_43) { RequestConfig config = RequestConfig.custom() .setSocketTimeout(readTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectTimeout) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setDefaultRequestConfig(config); <START> if (Boolean.getBoolean(USE_SYSTEM_PROPERTIES)) { <END> String proxyHost = System.getProperty("http.proxyHost"); Integer proxyPort = Integer.getInteger("http.proxyPort"); if (proxyHost != null && proxyPort != null) { clientBuilder.setRoutePlanner(new DefaultProxyRoutePlanner(new HttpHost(proxyHost, proxyPort))); } clientBuilder.useSystemProperties(); } return clientBuilder.build(); } else { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); return httpClient; } }</code><technical_language>done HTTP_CLIENT_API_43 client.... this is false proxy</technical_language>

Target:
protected HttpClient getHttpClient(Integer readTimeout, Integer connectTimeout) { if (getDoCacheClient() && HTTP_CLIENT_API_43) { if (cachedClient == null) { cachedClient = getNewPooledHttpClient(readTimeout, connectTimeout); } return cachedClient; } if (HTTP_CLIENT_API_43) { RequestConfig config = RequestConfig.custom() .setSocketTimeout(readTimeout) .setConnectTimeout(connectTimeout) .setConnectionRequestTimeout(connectTimeout) .build(); HttpClientBuilder clientBuilder = HttpClientBuilder.create() .setDefaultRequestConfig(config); if (Boolean.getBoolean(USE_SYSTEM_PROPERTIES)) { HttpRoutePlanner routePlanner = getRoutePlanner(); if (routePlanner != null) { clientBuilder.setRoutePlanner(routePlanner); } clientBuilder.useSystemProperties(); } return clientBuilder.build(); } else { DefaultHttpClient httpClient = new DefaultHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeout); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeout); if (Boolean.getBoolean(USE_SYSTEM_PROPERTIES)) { HttpRoutePlanner routePlanner = getRoutePlanner(); if (routePlanner != null) { httpClient.setRoutePlanner(routePlanner); } } return httpClient; } }
Source:
<code>private Filter buildAttributeFilter( String attributeName, Collection<String> attributeValues, boolean isExactMatch) { if (CollectionUtils.isEmpty(attributeValues)) { return null; } List<Filter> filters = new ArrayList<>(); for (String value : attributeValues) { if (isExactMatch) { filters.add(filterBuilder.attribute(attributeName).is().equalTo().text(value)); } else { <START> Filter f = filterBuilder.attribute(attributeName).is().like().text(value); <END> filters.add(f); } } if (filters.size() == 1) { return filters.get(0); } else { return filterBuilder.anyOf(filters); } }</code><technical_language>a more meaningful variable name</technical_language>

Target:
private Filter buildAttributeFilter( String attributeName, Collection<String> attributeValues, boolean isExactMatch) { if (CollectionUtils.isEmpty(attributeValues)) { return null; } List<Filter> filters = new ArrayList<>(); for (String value : attributeValues) { if (isExactMatch) { filters.add(filterBuilder.attribute(attributeName).is().equalTo().text(value)); } else { filters.add(filterBuilder.attribute(attributeName).is().like().text(value)); } } if (filters.size() == 1) { return filters.get(0); } else { return filterBuilder.anyOf(filters); } }
Source:
<code>public GatewayErrorException(String message) { super(message); this.responseFromGateway = "null"; <START> this.status = 0; <END> }</code><technical_language>defaulting zero, getStatus() return Optional<Integer></technical_language>

Target:
public GatewayErrorException(String message) { super(message); this.responseFromGateway = "null"; this.status = null; }
Source:
<code>void ensure_spies_are_created_for_nested_tests() { <START> MockUtil.getMockSettings(nestedSpy); <END> }</code><technical_language>add assertion this</technical_language>

Target:
void ensure_spies_are_created_for_nested_tests() { assertThat(MockUtil.isSpy(nestedSpy)).isTrue(); }
Source:
<code>public void addContentToIndex(final Contentlet content, final boolean includeDependencies, <START> final boolean indexBeforeCommit, <END> final boolean reindexOnly, final BulkRequestBuilder bulk) throws DotHibernateException { if (null == content || !UtilMethods.isSet(content.getIdentifier())) { return; } List<Contentlet> contentDependencies = null; final boolean indexNow = !content.isDefaultContentRefresh(); final List<Contentlet> contentToIndex = new ArrayList<>(); contentToIndex.add(content); try { if(includeDependencies){ if (indexNow) { contentDependencies = new ArrayList<>(loadDeps(content)); } else { contentToIndex.addAll(loadDeps(content)); } } if(bulk!=null || indexBeforeCommit) { if (indexNow) { this.handleIndexNow(content, reindexOnly, bulk, contentDependencies, contentToIndex, false); } else { this.indexContentList(contentToIndex, bulk, reindexOnly); } } else { if (indexNow) { this.handleIndexNow(content, reindexOnly, bulk, contentDependencies, contentToIndex, true); } else { HibernateUtil.addCommitListener(content.getInode() + ReindexRunnable.Action.ADDING, new AddReindexRunnable(contentToIndex, ReindexRunnable.Action.ADDING, bulk, reindexOnly)); } } } catch (DotDataException | DotSecurityException e1) { throw new DotHibernateException(e1.getMessage(), e1); } }</code><technical_language>do need indexBeforeCommit flag? If contentlet refresh is wait true indexes now, if is a commit listener used</technical_language>

Target:
public void addContentToIndex(final Contentlet content, final boolean includeDependencies, final boolean indexBeforeCommit, final boolean reindexOnly, final BulkRequestBuilder bulk) throws DotHibernateException { if (null == content || !UtilMethods.isSet(content.getIdentifier())) { return; } List<Contentlet> contentDependencies = null; final boolean indexIsNotDefer = IndexPolicy.DEFER != content.getIndexPolicy(); final List<Contentlet> contentToIndex = new ArrayList<>(); contentToIndex.add(content); try { if(includeDependencies){ if (indexIsNotDefer) { contentDependencies = new ArrayList<>(loadDeps(content)); } else { contentToIndex.addAll(loadDeps(content)); } } if(bulk!=null || indexBeforeCommit) { if (indexIsNotDefer) { this.handleIndexNotDefer(content, reindexOnly, bulk, contentDependencies, contentToIndex, false); } else { this.indexContentList(contentToIndex, bulk, reindexOnly); } } else { if (indexIsNotDefer) { this.handleIndexNotDefer(content, reindexOnly, bulk, contentDependencies, contentToIndex, true); } else { HibernateUtil.addCommitListener(content.getInode() + ReindexRunnable.Action.ADDING, new AddReindexRunnable(contentToIndex, ReindexRunnable.Action.ADDING, bulk, reindexOnly)); } } } catch (DotDataException | DotSecurityException e1) { throw new DotHibernateException(e1.getMessage(), e1); } }
Source:
<code>public boolean equals(Object other) { if (other == null) { return false; } if (!(other instanceof JcrResourceAdapter)) { return false; } return other == this; <START> } <END></code><technical_language>Again, this written more concisely: public boolean equals(Object other) { if ( other == this ) return true; if ( other instanceof JcrResourceAdapter ) return true; return false; }</technical_language>

Target:
public boolean equals(Object other) { if (other == this) { return true; } if (other instanceof JcrManagedConnectionFactory) { return this == other; } return false; }
Source:
<code>Index apply(InputStream t) throws IOException; } <START> IndexType(final int magicNumber, final Integer tribbleIndexType, boolean canCreate, IndexFromStreamFunction createFromInputStream, final int defaultBinSize) { <END> this.magicNumber = magicNumber; this.tribbleIndexType = tribbleIndexType; this.canCreate = canCreate; this.createFromInputStream = createFromInputStream; this.defaultBinSize = defaultBinSize; }</code><technical_language>Nit: couple of missing finals</technical_language>

Target:
Index apply(InputStream t) throws IOException; } IndexType(final int magicNumber, final Integer tribbleIndexType, final boolean canCreate, final IndexFromStreamFunction createFromInputStream, final int defaultBinSize) { this.magicNumber = magicNumber; this.tribbleIndexType = tribbleIndexType; this.canCreate = canCreate; this.createFromInputStream = createFromInputStream; this.defaultBinSize = defaultBinSize; }
Source:
<code>private Function<PollingContext<OperationResult>, Mono<OperationResult>> receiptAnalyzeActivationOperation( String sourceUrl, boolean includeTextDetails) { return (pollingContext) -> { try { return service.analyzeReceiptAsyncWithResponseAsync(includeTextDetails, new SourcePath().setSource(sourceUrl)) .map(response -> { <START> final AnalyzeReceiptAsyncHeaders headers = response.getDeserializedHeaders(); <END> return new OperationResult(parseModelId(headers.getOperationLocation())); }); } catch (RuntimeException ex) { return monoError(logger, ex); } }; }</code><technical_language>NIT: headers once</technical_language>

Target:
private Function<PollingContext<OperationResult>, Mono<OperationResult>> receiptAnalyzeActivationOperation( String sourceUrl, boolean includeTextDetails) { return (pollingContext) -> { try { return service.analyzeReceiptAsyncWithResponseAsync(includeTextDetails, new SourcePath().setSource(sourceUrl)) .map(response -> new OperationResult( parseModelId(response.getDeserializedHeaders().getOperationLocation()))); } catch (RuntimeException ex) { return monoError(logger, ex); } }; }
Source:
<code>public Map<String, String> getUAMap(String uaString) { result.clear(); UserAgent browser = null; Device device = null; OS os = null; if (uaString == null) uaString = ""; try { Client c = cachingParser.parse(uaString); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } catch (Exception e) { LOG.error(e.getMessage(), e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } <START> result.put("wmf_app_version", NA); <END> String wmfAppStart = "WikipediaApp/"; if (uaString.startsWith(wmfAppStart)) { int from = wmfAppStart.length(); int to = uaString.indexOf(' ', from); if (to > from) result.put("wmf_app_version", uaString.substring(from, to)); else result.put("wmf_app_version", uaString.substring(from, uaString.length())); } return result; }</code><technical_language>Here, this executed for requests. If in else clause, executed for non-WikipediaApp requests. I a big difference... is a reason put this out of else statement</technical_language>

Target:
public Map<String, String> getUAMap(String uaString) { result.clear(); UserAgent browser = null; Device device = null; OS os = null; if (uaString == null) uaString = ""; try { Client c = cachingParser.parse(uaString); if (c != null) { browser = c.userAgent; device = c.device; os = c.os; } } catch (Exception e) { LOG.error(e.getMessage(), e); } if (browser != null) { result.put("browser_family", replaceNA(browser.family)); result.put("browser_major", replaceNA(browser.major)); } else { result.put("browser_family", NA); result.put("browser_major", NA); } if (device != null) { result.put("device_family", replaceNA(device.family)); } else { result.put("device_family", NA); } if (os != null) { result.put("os_family", replaceNA(os.family)); result.put("os_major", replaceNA(os.major)); result.put("os_minor", replaceNA(os.minor)); } else { result.put("os_family", NA); result.put("os_major", NA); result.put("os_minor", NA); } String wmfAppVersion = NA; String wmfAppStart = "WikipediaApp/"; if (uaString.startsWith(wmfAppStart)) { int from = wmfAppStart.length(); int to = uaString.indexOf(' ', from); to = (to == -1) ? uaString.length() : to; wmfAppVersion = uaString.substring(from, to); } result.put("wmf_app_version", wmfAppVersion); return result; }
Source:
<code>public static <N, V extends Number> ValueGraph<N, V> extractFrom(ValueGraph<N, V> graph) { Set<N> remainingNodes = new HashSet<>(graph.nodes()); Map<N, NodeData<N>> nodeData = new HashMap<>(); for (N node : remainingNodes) { nodeData.put(node, new NodeData<>()); } MapBinaryHeap<N> heap = new MapBinaryHeap<>((a, b) -> Double.compare(nodeData.get(a).cost, nodeData.get(b).cost)); heap.addAll(remainingNodes); MutableValueGraph<N, V> tree = ValueGraphBuilder.directed().build(); while (!remainingNodes.isEmpty()) { N node = heap.peek(); remainingNodes.remove(node); N connectedNode = nodeData.get(node).connection; if (connectedNode == null) { tree.addNode(node); } else { tree.putEdgeValue( node, connectedNode, <START> graph.edgeValue(node, connectedNode).orElseThrow(IllegalStateException::new)); <END> } for (N adjacentNode : graph.adjacentNodes(node)) { if (!remainingNodes.contains(adjacentNode)) { continue; } NodeData<N> adjacentNodeData = nodeData.get(adjacentNode); double connectingEdgeWeight = graph .edgeValue(node, adjacentNode) .orElseThrow(IllegalStateException::new) .doubleValue(); if (connectingEdgeWeight < adjacentNodeData.cost) { adjacentNodeData.update(connectingEdgeWeight, node); heap.update(adjacentNode); } } } return tree; }</code><technical_language>Minor nit: if (in effect) converting this a NoSuchElementException IllegalStateException, add a message tells user this is a bug in library, in code. replacing mysterious exception another. :)</technical_language>

Target:
public static <N, V extends Number> ValueGraph<N, V> extractFrom(ValueGraph<N, V> graph) { Set<N> remainingNodes = new HashSet<>(graph.nodes()); Map<N, NodeData<N>> nodeData = new HashMap<>(); for (N node : remainingNodes) { nodeData.put(node, new NodeData<>()); } MapBinaryHeap<N> heap = new MapBinaryHeap<>((a, b) -> Double.compare(nodeData.get(a).cost, nodeData.get(b).cost)); heap.addAll(remainingNodes); MutableValueGraph<N, V> tree = ValueGraphBuilder.directed().build(); while (!remainingNodes.isEmpty()) { N node = heap.peek(); remainingNodes.remove(node); N connectedNode = nodeData.get(node).connection; if (connectedNode == null) { tree.addNode(node); } else { tree.putEdgeValue( node, connectedNode, graph .edgeValue(node, connectedNode) .orElseThrow( () -> new IllegalStateException( "unexpected exception caused by bug in graph data structures"))); } for (N adjacentNode : graph.adjacentNodes(node)) { if (!remainingNodes.contains(adjacentNode)) { continue; } NodeData<N> adjacentNodeData = nodeData.get(adjacentNode); double connectingEdgeWeight = graph .edgeValue(node, adjacentNode) .orElseThrow( () -> new IllegalStateException( "unexpected exception caused by bug in graph data structures")) .doubleValue(); if (connectingEdgeWeight < adjacentNodeData.cost) { adjacentNodeData.update(connectingEdgeWeight, node); heap.update(adjacentNode); } } } return tree; }
Source:
<code>public void restrictedLoginDialogLinkTest() { String link = Locale.getDefault().getLanguage().equals(Locale.GERMAN.getLanguage()) ? Constants.RESTRICTED_LOGIN_LINK_GERMAN <START> : baseActivityTestRule.getActivity().getString(R.string.schoolreg_link); <END> Intents.init(); Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(link)); intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null)); Espresso.onView(ViewMatchers.withId(R.id.dialog_restricted_login_text)) .perform(ViewActions.openLinkWithText(link)); intended(expectedIntent); Intents.release(); }</code><technical_language>please getResourcesString uitestutils</technical_language>

Target:
public void restrictedLoginDialogLinkTest() { String link = Locale.getDefault().getLanguage().equals(Locale.GERMAN.getLanguage()) ? UiTestUtils.getResourcesString(R.string.schoolreg_link_german) : UiTestUtils.getResourcesString(R.string.schoolreg_link); Intents.init(); Matcher<Intent> expectedIntent = allOf(hasAction(Intent.ACTION_VIEW), hasData(link)); intending(expectedIntent).respondWith(new Instrumentation.ActivityResult(0, null)); Espresso.onView(ViewMatchers.withId(R.id.dialog_restricted_login_text)) .perform(ViewActions.openLinkWithText(link)); intended(expectedIntent); Intents.release(); }
Source:
<code>public Iterable<Edge> getEdges(final Vertex otherVertex, Direction direction, String label, FetchHints fetchHints, Authorizations authorizations) { <START> getFetchHints().validateHasEdgeFetchHints(direction); <END> return getGraph().getEdges(getEdgeIdsWithOtherVertexId(otherVertex.getId(), direction, labelToArrayOrNull(label), authorizations), fetchHints, authorizations); }</code><technical_language>checking label</technical_language>

Target:
public Iterable<Edge> getEdges(final Vertex otherVertex, Direction direction, String label, FetchHints fetchHints, Authorizations authorizations) { getFetchHints().validateHasEdgeFetchHints(direction, label); return getGraph().getEdges(getEdgeIdsWithOtherVertexId(otherVertex.getId(), direction, labelToArrayOrNull(label), authorizations), fetchHints, authorizations); }
Source:
<code>public static void registerPermission(final String permissionNode, final int opLevel) { <START> if (!REGISTERED_PERMISSIONS.contains(permissionNode)) { <END> SpongeCommon.getLogger().info("Registering permission with op level {}.", permissionNode, opLevel); REGISTERED_PERMISSIONS.add(permissionNode); final PermissionService service = SpongeCommon.getGame().getServiceProvider().permissionService(); if (opLevel == 0) { service.getDefaults() .getTransientSubjectData() .setPermission(SubjectData.GLOBAL_CONTEXT, permissionNode, Tristate.TRUE); } if (service instanceof SpongePermissionService) { ((SpongePermissionService) service).getGroupForOpLevel(opLevel).getTransientSubjectData() .setPermission(SubjectData.GLOBAL_CONTEXT, permissionNode, Tristate.TRUE); } } }</code><technical_language>if (!contains) add -> if (add)</technical_language>

Target:
public static void registerPermission(final String permissionNode, final int opLevel) { if (REGISTERED_PERMISSIONS.add(permissionNode)) { final PermissionService service = SpongeCommon.getGame().getServiceProvider().permissionService(); if (opLevel == 0) { service.getDefaults() .getTransientSubjectData() .setPermission(SubjectData.GLOBAL_CONTEXT, permissionNode, Tristate.TRUE); } if (service instanceof SpongePermissionService) { ((SpongePermissionService) service).getGroupForOpLevel(opLevel).getTransientSubjectData() .setPermission(SubjectData.GLOBAL_CONTEXT, permissionNode, Tristate.TRUE); } } }
Source:
<code>public String getRelativePath() { <START> String path = getPath(); <END> if (path.startsWith("/")) { path = path.substring(1); } return path; }</code><technical_language>Yes, this work. If I understand correctly, this is run gwt... right? support File::getCanonicalPath()? if it... If not... I a more generic... path.replace("//", "/") conditional..</technical_language>

Target:
public String getRelativePath() { String path = getPath(); return path.startsWith("/") ? path.substring(1) : path; }
Source:
<code>OffPeakHoursImpl(int startHour, int endHour) { this.startHour = startHour; this.endHour = endHour; <START> LOG.info(this.toString()); <END> }</code><technical_language>log is good, do info region</technical_language>

Target:
OffPeakHoursImpl(int startHour, int endHour) { this.startHour = startHour; this.endHour = endHour; }
Source:
<code>protected Session getSession() { SessionFactory sessionFactory = HibernateUtil.getSessionFactory(); <START> return sessionFactory.openSession(); <END> }</code><technical_language>this reduced a single line</technical_language>

Target:
protected Session getSession() { return HibernateUtil.getSessionFactory().openSession(); }
Source:
<code>public List<Consumer> getHypervisorsBulk(Collection<String> hypervisorIds, String ownerKey) { if (hypervisorIds == null || hypervisorIds.isEmpty()) { return new LinkedList<Consumer>(); } LinkedList<String> hypervisorIdsUpper = new LinkedList<String>(); for (String hypervisorId : hypervisorIds) { hypervisorIdsUpper.add(hypervisorId.toUpperCase()); } String query = "SELECT c FROM Consumer c WHERE" + <START> "(c.owner.key = :ownerKey AND UPPER(c.hypervisorId.hypervisorId) IN (:hypervisorIds))" + <END> "ORDER BY c.hypervisorId.hypervisorId ASC"; List<Consumer> consumers = getEntityManager().createQuery(query) .setLockMode(LockModeType.PESSIMISTIC_WRITE) .setParameter("ownerKey", ownerKey) .setParameter("hypervisorIds", hypervisorIdsUpper) .getResultList(); return consumers; }</code><technical_language>Potential IN operator limit issue</technical_language>

Target:
public List<Consumer> getHypervisorsBulk(Collection<String> hypervisorIds, String ownerKey) { if (hypervisorIds == null || hypervisorIds.isEmpty()) { return new LinkedList<Consumer>(); } LinkedList<String> hypervisorIdsUpper = new LinkedList<String>(); for (String hypervisorId : hypervisorIds) { hypervisorIdsUpper.add(hypervisorId.toUpperCase()); } List<Consumer> consumers = new LinkedList<Consumer>(); String query = "SELECT c FROM Consumer c WHERE " + "(c.owner.key = :ownerKey AND UPPER(c.hypervisorId.hypervisorId) IN (:hypervisorIds)) " + "ORDER BY c.hypervisorId.hypervisorId ASC"; javax.persistence.Query q = getEntityManager().createQuery(query); java.util.Collections.sort(hypervisorIdsUpper); int fromIndex = 0; int toIndex = fromIndex + MAX_IN_QUERY_LENGTH; while (fromIndex < hypervisorIdsUpper.size()) { if (toIndex > hypervisorIdsUpper.size()) { toIndex = hypervisorIdsUpper.size(); } List<String> subList = hypervisorIdsUpper.subList(fromIndex, toIndex); q.setLockMode(LockModeType.PESSIMISTIC_WRITE); q.setParameter("ownerKey", ownerKey); q.setParameter("hypervisorIds", subList); consumers.addAll(q.getResultList()); fromIndex = toIndex; toIndex += MAX_IN_QUERY_LENGTH; } return consumers; }
Source:
<code>protected SelectionAdapter createMandatoryAttributesSelectionListener(final IObservableSet checkedElements) { return new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { checkMandatoryAttributes(checkedElements, mappings); } protected void checkMandatoryAttributes(final IObservableSet checkedElements, final List<FieldToContractInputMapping> mappings) { for (final FieldToContractInputMapping mapping : mappings) { if (!mapping.getField().isNullable() && !mapping.isGenerated()) { checkedElements.add(mapping); checkAllMappings(checkedElements, mapping.getChildren()); generateAllMappings(mapping.getChildren(), true); <START> if (mapping.getParent() != null && !checkedElements.contains(mapping.getParent())) { <END> checkedElements.add(mapping.getParent()); } } checkMandatoryAttributes(checkedElements, mapping.getChildren()); } } }; }</code><technical_language>mapping.getParent extracted avriable</technical_language>

Target:
protected SelectionAdapter createMandatoryAttributesSelectionListener(final IObservableSet checkedElements) { return new SelectionAdapter() { @Override public void widgetSelected(final SelectionEvent e) { checkMandatoryAttributes(checkedElements, mappings); } protected void checkMandatoryAttributes(final IObservableSet checkedElements, final List<FieldToContractInputMapping> mappings) { for (final FieldToContractInputMapping mapping : mappings) { final List<FieldToContractInputMapping> mappingChildren = mapping.getChildren(); if (!mapping.getField().isNullable() && !mapping.isGenerated()) { checkedElements.add(mapping); mapping.setGenerated(true); checkAllMappings(checkedElements, mappingChildren); generateAllMappings(mappingChildren, true); } if (mapping.isGenerated()) { checkMandatoryAttributes(checkedElements, mappingChildren); checkMandatoryAttributes(checkedElements, mappingChildren); } } } }; }
Source:
<code>public void updatePermissionWithExclusiveConsumer(String queueName, QueueRolePermission[] queueRolePermissionsDTO, boolean exclusiveConsumerUpdate) throws BrokerManagerAdminException{ QueueManagerService queueManagerService = AndesBrokerManagerAdminServiceDSHolder.getInstance() .getQueueManagerService(); try { queueManagerService.updateExclusiveConsumerValue(queueName, exclusiveConsumerUpdate); } catch (QueueManagerException e) { <START> e.printStackTrace(); <END> } updatePermission(queueName, queueRolePermissionsDTO); }</code><technical_language>Done e.printStackTrace(); . throw exception. this is a service, I suggest log exception throw</technical_language>

Target:
public void updatePermissionWithExclusiveConsumer(String queueName, QueueRolePermission[] queueRolePermissionsDTO, boolean exclusiveConsumerUpdate) throws BrokerManagerAdminException, QueueManagerException { QueueManagerService queueManagerService = AndesBrokerManagerAdminServiceDSHolder.getInstance() .getQueueManagerService(); try { queueManagerService.updateExclusiveConsumerValue(queueName, exclusiveConsumerUpdate); updatePermission(queueName, queueRolePermissionsDTO); } catch (QueueManagerException e) { log.error("Error in updating exclusive consumer value", e); throw new BrokerManagerAdminException("Error in updating exclusive consumer value.", e); } }
Source:
<code>public XformParser getParser(ConfigurationType type) { switch (type) { case ONA: return new XformParserODK(); case ODK: return new XformParserODK(); case KOBO: return new XformParserKobo(); default: <START> return null; <END> } }</code><technical_language>more raise a configuration exception here? This lead null pointer exception i</technical_language>

Target:
public XformParser getParser(ConfigurationType type) throws ConfigurationTypeException { switch (type) { case ONA: return new XformParserODK(); case ODK: return new XformParserODK(); case KOBO: return new XformParserKobo(); default: throw new ConfigurationTypeException("No parser for configuration type: " + type); } }
Source:
<code>public void testDefaults() { <START> ConfigAssertions.assertRecordedDefaults(ConfigAssertions.recordDefaults(SqlEnvironmentConfig.class) <END> .setPath(" ")); }</code><technical_language>static import assert methods this line, this becomes: assertRecordedDefaults(recordDefaults(SqlEnvironmentConfig.class).setPath(" "));</technical_language>

Target:
public void testDefaults() { assertRecordedDefaults(recordDefaults(SqlEnvironmentConfig.class) .setPath(null)); }
Source:
<code>protected File checkForIndex(HttpServletRequest request, HttpServletResponse response, File file, String path) throws IOException { <START> if (null != file && file.isDirectory()) { <END> File index = new File(file, INDEX); log.info("Index is \"" + index.getAbsolutePath() + "\"."); if (index.isFile()) { String redirect = null; if (path == null) { redirect = request.getServletPath() + "/" + INDEX; } else { redirect = request.getServletPath() + path + "/" + INDEX; } response.sendRedirect(redirect); file = new File(file, INDEX); } else { log.error("There is no index page for directory \"" + file.getAbsolutePath() + "\", will send a 404 error response."); file = null; } } else if (!ServletUtils.canReadFile(file)) { file = null; } return file; }</code><technical_language>Please "something <operator> null" convention</technical_language>

Target:
protected File checkForIndex(HttpServletRequest request, HttpServletResponse response, File file, String path) throws IOException { if (file != null && file.isDirectory()) { File index = new File(file, INDEX); log.info("Index is \"" + index.getAbsolutePath() + "\"."); if (index.isFile()) { String redirect = null; if (path == null) { redirect = request.getServletPath() + "/" + INDEX; } else { redirect = request.getServletPath() + path + "/" + INDEX; } response.sendRedirect(redirect); file = new File(file, INDEX); } else { log.error("There is no index page for directory \"" + file.getAbsolutePath() + "\", will send a 404 error response."); file = null; } } else if (!ServletUtils.canReadFile(file)) { file = null; } return file; }
Source:
<code><START> public String toString() { <END> return "ForceWriteRequest{" + "forceWriteWaiters=" + forceWriteWaiters + ", shouldClose=" + shouldClose + ", isMarker=" + isMarker + ", lastFlushedPosition=" + lastFlushedPosition + ", logId=" + logId + '}'; }</code><technical_language>StringBuilder. lomok ToString annotation guava ToStringHelper</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(ForceWriteRequest.class) .add("forceWriteWaiters", forceWriteWaiters) .add("shouldClose", shouldClose) .add("isMarker", isMarker) .add("lastFlushedPosition", lastFlushedPosition) .add("logId", logId) .toString(); }
Source:
<code>public void run() { try { startupComplete(); while (isRunning()) { configureNewConnections(); processNewResponses(); selector.poll(300); List<NetworkReceive> completedReceives = selector.completedReceives(); for (NetworkReceive networkReceive : completedReceives) { SelectionKey key = selector.keyForId(networkReceive.getConnectionId()); SocketServerRequest req = new SocketServerRequest(id, key, new ByteBufferInputStream(networkReceive.getReceivedBytes().getPayload())); channel.sendRequest(req); } List<NetworkSend> completedSends = selector.completedSends(); for (NetworkSend networkSend : completedSends) { networkSend.onSendComplete(); metrics.sendInFlight.dec(); } } } catch (Exception e) { <START> logger.error("Error while shutting down processor thread {}", e); <END> } finally { logger.debug("Closing server socket and selector."); closeAll(); shutdownComplete(); } }</code><technical_language>a question relating patch. Exception thrown due reasons right</technical_language>

Target:
public void run() { try { startupComplete(); while (isRunning()) { configureNewConnections(); processNewResponses(); selector.poll(pollTimeoutMs); List<NetworkReceive> completedReceives = selector.completedReceives(); for (NetworkReceive networkReceive : completedReceives) { String connectionId = networkReceive.getConnectionId(); SocketServerRequest req = new SocketServerRequest(id, connectionId, new ByteBufferInputStream(networkReceive.getReceivedBytes().getPayload())); channel.sendRequest(req); } } } catch (Exception e) { logger.error("Error in processor thread {}", e); } finally { logger.debug("Closing server socket and selector."); closeAll(); shutdownComplete(); } }
Source:
<code>public void test19CloseImportedProjectsZipFile() throws Exception { WizardProjectsImportPage wpip = createImportWizardWithZipLocation( "ImportExistingProjectsWizardTestRebuildProject"); try (AutoCloseable restore = setPageSetting(wpip, "WizardProjectsImportPage.STORE_CLOSE_CREATED_PROJECTS_ID", true)) { wpip.createProjects(); IProject testProject = ResourcesPlugin.getWorkspace().getRoot() .getProject("ImportExistingProjectsWizardTestRebuildProject"); assertFalse("Expected imported project to be <START> closd due <END> to setting dialog option checkbox", testProject.isAccessible()); } }</code><technical_language>typo. "closed"</technical_language>

Target:
public void test19CloseImportedProjectsZipFile() throws Exception { ImportTestUtils.deleteWorkspaceProjects(); WizardProjectsImportPage wpip = getNewWizard(); try (AutoCloseable restore = setPageSetting(wpip, "WizardProjectsImportPage.STORE_CLOSE_CREATED_PROJECTS_ID", true)) { useDataLocationProject(wpip, "ImportExistingProjectsWizardTestRebuildProject"); assertTrue("Failed to import project", wpip.createProjects()); IProject testProject = ResourcesPlugin.getWorkspace().getRoot() .getProject("ImportExistingProjectsWizardTestRebuildProject"); assertTrue("Failed to import test project", testProject.exists()); assertFalse("Expected imported project to be closed due to setting dialog option checkbox", testProject.isOpen()); } }
Source:
<code>public WebArchive createDeployment() { <START> if (resourceLocal) { <END> archive.addClasses( MemberRegistrationWithResourceLocal.class, ResourceLocalResources.class ); } else { archive.addClasses( MemberRegistrationWithJta.class, JtaResources.class ); } return archive; }</code><technical_language>Interesting approach. I guess qualifiers CDI alternative mechanism, this simplest</technical_language>

Target:
public WebArchive createDeployment() { if (resourceLocal) { archive.addClasses( MemberRegistrationWithResourceLocal.class ); } else { archive.addClasses( MemberRegistrationWithJta.class, JtaResources.class ); } return archive; }
Source:
<code>public void testUnclassifiedReviewArtifactIsntFiltered() { ITask task = mock(ITask.class); <START> when(task.getAttribute("ARTIFACT")).thenReturn(null); <END> TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasntFiltered = filter.select(null, task); Assert.assertTrue(wasntFiltered); }</code><technical_language>need this line mocks return null specified</technical_language>

Target:
public void testUnclassifiedReviewArtifactIsntFiltered() { ITask task = mock(ITask.class); TaskReviewArtifactFilter filter = new TaskReviewArtifactFilter(); boolean wasFiltered = !filter.select(null, task); assertFalse(wasFiltered); }
Source:
<code>private static Optional<EqualsOperands> getEqualMethodInvocationOperands(ExpressionTree expressionTree) { if(!expressionTree.is(Tree.Kind.METHOD_INVOCATION)) { <START> return Optional.empty(); <END> } MethodInvocationTree mit = (MethodInvocationTree) expressionTree; Symbol symbol = mit.symbol(); ExpressionTree methodSelect = mit.methodSelect(); if (mit.arguments().size() == 1) { ExpressionTree arg = mit.arguments().get(0); if ("equals".equals(symbol.name()) && arg.symbolType().is("java.lang.String") && methodSelect.is(Tree.Kind.MEMBER_SELECT)) { ExpressionTree expression = ((MemberSelectExpressionTree) methodSelect).expression(); if (arg.is(Tree.Kind.STRING_LITERAL) && expression.is(Tree.Kind.IDENTIFIER)) { return Optional.of(new EqualsOperands((LiteralTree) arg, (IdentifierTree) expression)); } else if (arg.is(Tree.Kind.IDENTIFIER) && expression.is(Tree.Kind.STRING_LITERAL)) { return Optional.of(new EqualsOperands((LiteralTree) expression, (IdentifierTree) arg)); } } } return Optional.empty(); }</code><technical_language>covers test cases done "==", ones, people necessarily equals() form time. void foo(String s) { if ("hello" == s) { // ... } else if (s == "world") { // inverted case // ... } else if ("foo" == s) { // ... } else { // ... } }</technical_language>

Target:
private static Optional<EqualsOperands> getEqualMethodInvocationOperands(ExpressionTree expressionTree) { ExpressionTree arg = null; ExpressionTree expression = null; if (expressionTree.is(Tree.Kind.METHOD_INVOCATION)) { MethodInvocationTree mit = (MethodInvocationTree) expressionTree; Symbol symbol = mit.symbol(); ExpressionTree methodSelect = mit.methodSelect(); if (mit.arguments().size() == 1) { arg = mit.arguments().get(0); if ("equals".equals(symbol.name()) && arg.symbolType().is("java.lang.String") && methodSelect.is(Tree.Kind.MEMBER_SELECT)) { expression = ((MemberSelectExpressionTree) methodSelect).expression(); } } } else if (expressionTree.is(Tree.Kind.EQUAL_TO)) { BinaryExpressionTree equalTo = (BinaryExpressionTree) expressionTree; arg = equalTo.leftOperand(); expression = equalTo.rightOperand(); } if (arg != null && expression != null) { if (arg.is(Tree.Kind.STRING_LITERAL) && expression.is(Tree.Kind.IDENTIFIER)) { return Optional.of(new EqualsOperands((LiteralTree) arg, (IdentifierTree) expression)); } else if (arg.is(Tree.Kind.IDENTIFIER) && expression.is(Tree.Kind.STRING_LITERAL)) { return Optional.of(new EqualsOperands((LiteralTree) expression, (IdentifierTree) arg)); } } return Optional.empty(); }
Source:
<code>public DiagnosticReport getFHIRDiagnosticReport(Encounter omrsiagnosticReport) { log.info("Laboratory Handler : GetFHIRDiagnosticReport"); DiagnosticReport diagnosticReport = new DiagnosticReport(); EncounterService omrsEncounterService = Context.getEncounterService(); diagnosticReport.setId(new IdDt("DiagnosticReport", omrsiagnosticReport.getUuid())); diagnosticReport.setIssued(new DateTimeDt(omrsiagnosticReport.getEncounterDatetime())); org.openmrs.Patient omrsPatient = omrsiagnosticReport.getPatient(); diagnosticReport.getSubject().setResource(FHIRPatientUtil.generatePatient(omrsPatient)); <START> String encounterRoleUuid = "73bbb069-9781-4afc-a9d1-54b6b2270e03"; <END> EncounterRole omrsEncounterRole = omrsEncounterService.getEncounterRoleByUuid(encounterRoleUuid); Set<Provider> omrsProviderList = omrsiagnosticReport.getProvidersByRole(omrsEncounterRole); if (!omrsProviderList.isEmpty()) { Practitioner practitioner = FHIRPractitionerUtil.generatePractitioner(omrsProviderList.iterator().next()); diagnosticReport.getPerformer().setResource(practitioner); } String serviceCategory = omrsiagnosticReport.getEncounterType().getName(); List<CodingDt> serviceCategoryList = new ArrayList<CodingDt>(); serviceCategoryList.add(new CodingDt("<LINK_0>", serviceCategory)); diagnosticReport.getServiceCategory().setCoding(serviceCategoryList); return diagnosticReport; }</code><technical_language>hard coded</technical_language>

Target:
private DiagnosticReport getFHIRDiagnosticReport(Encounter omrsiagnosticReport) { log.info("Laboratory Handler : GetFHIRDiagnosticReport"); DiagnosticReport diagnosticReport = new DiagnosticReport(); EncounterService omrsEncounterService = Context.getEncounterService(); diagnosticReport.setId(new IdDt("DiagnosticReport", omrsiagnosticReport.getUuid())); diagnosticReport.setIssued(new DateTimeDt(omrsiagnosticReport.getEncounterDatetime())); org.openmrs.Patient omrsPatient = omrsiagnosticReport.getPatient(); diagnosticReport.getSubject().setResource(FHIRPatientUtil.generatePatient(omrsPatient)); String encounterRoleUuid = "73bbb069-9781-4afc-a9d1-54b6b2270e03"; EncounterRole omrsEncounterRole = omrsEncounterService.getEncounterRoleByUuid(encounterRoleUuid); Set<Provider> omrsProviderList = omrsiagnosticReport.getProvidersByRole(omrsEncounterRole); if (!omrsProviderList.isEmpty()) { Practitioner practitioner = FHIRPractitionerUtil.generatePractitioner(omrsProviderList.iterator().next()); diagnosticReport.getPerformer().setResource(practitioner); } String serviceCategory = omrsiagnosticReport.getEncounterType().getName(); List<CodingDt> serviceCategoryList = new ArrayList<CodingDt>(); serviceCategoryList.add(new CodingDt("<LINK_0>", serviceCategory)); diagnosticReport.getServiceCategory().setCoding(serviceCategoryList); return diagnosticReport; }
Source:
<code>public String getMapTitle(int mapIndex) { String mapTitle = mapTitleList.get(mapIndex).getText(); <START> return mapTitle; <END> }</code><technical_language>return in line</technical_language>

Target:
public String getMapTitle(int mapIndex) { return mapTitleList.get(mapIndex).getText(); }
Source:
<code>public void beforeClass(final @Optional String testType) throws IOException { config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); <START> if (testType.equals("buckets")) { <END> testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); } else { testPathPrefix = IntegrationTestConfigContext.generateBasePathWithoutSeparator(config, testName); } IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }</code><technical_language>testType null, invert equals() check so: java if ("buckets".equals(testType)) {</technical_language>

Target:
public void beforeClass(final @Optional String testType) throws IOException { config = new IntegrationTestConfigContext(); final String testName = this.getClass().getSimpleName(); mantaClient = new MantaClient(config); if ("buckets".equals(testType)) { testPathPrefix = IntegrationTestHelper.setupTestPath(config, mantaClient, testName, testType); } else { testPathPrefix = IntegrationTestConfigContext.generateBasePathWithoutSeparator(config, testName); } IntegrationTestHelper.createTestBucketOrDirectory(mantaClient, testPathPrefix, testType); }
Source:
<code>private void populateCPUList(ClusterModel clusterModel, List<ServerCpu> cpus, boolean canChangeArchitecture) { ServerCpu oldSelectedCpu = clusterModel.getCPU().getSelectedItem(); clusterModel.getCPU().setItems(cpus); initSupportedArchitectures(clusterModel); clusterModel.getCPU().setSelectedItem(oldSelectedCpu != null ? Linq.firstOrDefault(cpus, new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())) : null); if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized) { initCPU(); } if (clusterModel.getIsEdit()) { if (!canChangeArchitecture) { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(clusterModel.getEntity() .getArchitecture()))); } ArchitectureType oldSelectedArch = clusterModel.getArchitecture().getSelectedItem(); if (oldSelectedArch != null) { getArchitecture().setSelectedItem(oldSelectedArch); } else { getArchitecture().setSelectedItem(getEntity().getArchitecture()); } } else { getArchitecture().setSelectedItem(ArchitectureType.undefined); <START> } <END> getArchitecture().setIsAvailable(ApplicationModeHelper.isModeSupported(ApplicationMode.VirtOnly)); }</code><technical_language>this removed</technical_language>

Target:
private void populateCPUList(ClusterModel clusterModel, List<ServerCpu> cpus, boolean canChangeArchitecture) { ServerCpu oldSelectedCpu = clusterModel.getCPU().getSelectedItem(); clusterModel.getCPU().setItems(cpus); initSupportedArchitectures(clusterModel); clusterModel.getCPU().setSelectedItem(oldSelectedCpu != null ? Linq.firstOrDefault(cpus, new Linq.ServerCpuPredicate(oldSelectedCpu.getCpuName())) : null); if (clusterModel.getCPU().getSelectedItem() == null || !isCPUinitialized) { initCPU(); } if (clusterModel.getIsEdit()) { if (!canChangeArchitecture) { getArchitecture().setItems(new ArrayList<ArchitectureType>(Arrays.asList(clusterModel.getEntity() .getArchitecture()))); } ArchitectureType oldSelectedArch = clusterModel.getArchitecture().getSelectedItem(); if (oldSelectedArch != null) { getArchitecture().setSelectedItem(oldSelectedArch); } else { getArchitecture().setSelectedItem(getEntity().getArchitecture()); } } else { getArchitecture().setSelectedItem(ArchitectureType.undefined); } }