auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private static void triggerBlockingRegisterNativeAllocation() throws Exception { final long startTime = System.currentTimeMillis(); final long finalizerTimeoutMs = VMRuntime.getRuntime().getFinalizerTimeoutMs(); final long quittingTime = startTime + finalizerTimeoutMs - <START> 2 * <END> MAX_EXPECTED_GC_DURATION_MS; long maxMem = Runtime.getRuntime().maxMemory(); int size = (int)(maxMem / 5); int allocationCount = 10; long total = 0; for (int i = 0; i < allocationCount && System.currentTimeMillis() < quittingTime; ++i) { runtime.registerNativeAllocation(size); total += size; } while (total > 0) { runtime.registerNativeFree(size); total -= size; } }</code><technical_language>is rationale this constant</technical_language>

Target:
private static void triggerBlockingRegisterNativeAllocation() throws Exception { final long startTime = System.currentTimeMillis(); final long finalizerTimeoutMs = VMRuntime.getRuntime().getFinalizerTimeoutMs(); final long quittingTime = startTime + finalizerTimeoutMs - MAX_EXPECTED_GC_DURATION_MS; long maxMem = Runtime.getRuntime().maxMemory(); int size = (int)(maxMem / 5); int allocationCount = 10; long total = 0; for (int i = 0; i < allocationCount && System.currentTimeMillis() < quittingTime; ++i) { runtime.registerNativeAllocation(size); total += size; } while (total > 0) { runtime.registerNativeFree(size); total -= size; } }
Source:
<code>private int getAvailableSize(Object inputStream, int expectedReadSize) throws IOException, InternalException { RandomAccessFile file = null; BufferedInputStream stream = null; if (inputStream instanceof RandomAccessFile) { file = (RandomAccessFile) inputStream; } else if (inputStream instanceof BufferedInputStream) { stream = (BufferedInputStream) inputStream; } else { <START> throw new InternalException("Unknown input stream. This should not happen. Please report"); <END> } long pos = 0; if (file != null) { pos = file.getFilePointer(); } else { stream.mark(expectedReadSize); } byte[] buf = new byte[16384]; int bytesToRead = buf.length; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < expectedReadSize) { if ((expectedReadSize - totalBytesRead) < bytesToRead) { bytesToRead = expectedReadSize - totalBytesRead; } if (file != null) { bytesRead = file.read(buf, 0, bytesToRead); } else { bytesRead = stream.read(buf, 0, bytesToRead); } if (bytesRead < 0) { break; } totalBytesRead += bytesRead; } if (file != null) { file.seek(pos); } else { stream.reset(); } return totalBytesRead; }</code><technical_language>Add Minio Java issues link <LINK_0></technical_language>

Target:
private int getAvailableSize(Object inputStream, int expectedReadSize) throws IOException, InternalException { RandomAccessFile file = null; BufferedInputStream stream = null; if (inputStream instanceof RandomAccessFile) { file = (RandomAccessFile) inputStream; } else if (inputStream instanceof BufferedInputStream) { stream = (BufferedInputStream) inputStream; } else { throw new InternalException("Unknown input stream. This should not happen. " + "Please report to <LINK_0>"); } long pos = 0; if (file != null) { pos = file.getFilePointer(); } else { stream.mark(expectedReadSize); } byte[] buf = new byte[16384]; int bytesToRead = buf.length; int bytesRead = 0; int totalBytesRead = 0; while (totalBytesRead < expectedReadSize) { if ((expectedReadSize - totalBytesRead) < bytesToRead) { bytesToRead = expectedReadSize - totalBytesRead; } if (file != null) { bytesRead = file.read(buf, 0, bytesToRead); } else { bytesRead = stream.read(buf, 0, bytesToRead); } if (bytesRead < 0) { break; } totalBytesRead += bytesRead; } if (file != null) { file.seek(pos); } else { stream.reset(); } return totalBytesRead; }
Source:
<code>public void start() { <START> regionNormalizerTracker.start(); <END> if (worker != null) { pool.submit(worker); } }</code><technical_language>Check started silly</technical_language>

Target:
public void start() { synchronized (startStopLock) { if (started) { return; } regionNormalizerTracker.start(); if (worker != null) { pool.submit(worker); } started = true; } }
Source:
<code>public ModelAndView handleList( @RequestParam(value = REQUEST_PARAMETER_QUERY, required = false) String query, @RequestParam(value = REQUEST_PARAMETER_LIMIT, required = false) Integer limit, @RequestParam(value = REQUEST_PARAMETER_OFFSET, required = false) Long offset, @RequestParam(value = REQUEST_PARAMETER_ORDER_BY, required = false) String orderBy, @RequestParam(value = REQUEST_PARAMETER_ASCENDING, required = false) Boolean ascending) { ModelAndView modelAndView = new ModelAndView("user/list"); final String attributes = "userName, name.givenName, name.familyName"; if (limit == null) { limit = DEFAULT_LIMIT; } if (orderBy == null) { orderBy = DEFAULT_SORT_BY; <START> ascending = DEFAULT_SORT_DIRECTION; <END> } SCIMSearchResult<User> userList = userService.searchUser(query, limit, offset, orderBy, ascending, attributes); PagingLinks pagingLinks = generatePagingLinks(userList, query, orderBy, ascending); modelAndView.addObject(MODEL_USER_LIST, userList); modelAndView.addObject(MODEL_SESSION_DATA, session); modelAndView.addObject(MODEL_PAGING_LINKS, pagingLinks); session.setQuery(query); session.setLimit(limit); session.setOffset(offset); session.setOrderBy(orderBy); session.setAscending(ascending); return modelAndView; }</code><technical_language>is in case orderBy == null ascending == false? change if orderBy = orderBy != null ? orderBy : DEFAULT_SORT_BY; (same for limit)</technical_language>

Target:
public ModelAndView handleList( @RequestParam(value = REQUEST_PARAMETER_QUERY, required = false) String query, @RequestParam(value = REQUEST_PARAMETER_LIMIT, required = false) Integer limit, @RequestParam(value = REQUEST_PARAMETER_OFFSET, required = false) Long offset, @RequestParam(value = REQUEST_PARAMETER_ORDER_BY, required = false) String orderBy, @RequestParam(value = REQUEST_PARAMETER_ASCENDING, required = false) Boolean ascending) { ModelAndView modelAndView = new ModelAndView("user/list"); final String attributes = "userName, name.givenName, name.familyName"; limit = limit == null ? DEFAULT_LIMIT : limit; orderBy = orderBy == null ? DEFAULT_SORT_BY : orderBy; ascending = ascending == null ? DEFAULT_SORT_DIRECTION : ascending; SCIMSearchResult<User> userList = userService.searchUser(query, limit, offset, orderBy, ascending, attributes); PagingLinks pagingLinks = generatePagingLinks(userList, query, orderBy, ascending); modelAndView.addObject(MODEL_USER_LIST, userList); modelAndView.addObject(MODEL_SESSION_DATA, session); modelAndView.addObject(MODEL_PAGING_LINKS, pagingLinks); session.setQuery(query); session.setLimit(limit); session.setOffset(offset); session.setOrderBy(orderBy); session.setAscending(ascending); return modelAndView; }
Source:
<code>private void assertInvalid(LockToken token) { LeasedLockToken leasedLockToken = (LeasedLockToken) token; <START> assertFalse(leasedLockToken.isValid(getIdentifiedTime())); <END> }</code><technical_language>here; assertThat for asserting needs (assertThat().isFalse()). a useful approach do generally right do (usually simply asserting is true false, collection asserts get a error message fails line)</technical_language>

Target:
private void assertInvalid(LockToken token) { LeasedLockToken leasedLockToken = (LeasedLockToken) token; assertThat(leasedLockToken.isValid(getIdentifiedTime())).isFalse(); }
Source:
<code>protected void channelRead0( ChannelHandlerContext ctx, T request ) throws Exception { log.debug( "Handling request %s", request ); StoreCopyFinishedResponse.Status responseStatus = StoreCopyFinishedResponse.Status.E_UNKNOWN; try { NeoStoreDataSource neoStoreDataSource = dataSource.get(); if ( !hasSameStoreId( request.expectedStoreId(), neoStoreDataSource ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_STORE_ID_MISMATCH; } else if ( !isTransactionWithinReach( request.requiredTransactionId() ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_TOO_FAR_BEHIND; asyncCheckpoint(); } else <START> { <END> File storeDir = neoStoreDataSource.getStoreDir(); try ( ResourceIterator<StoreFileMetadata> resourceIterator = files( request, neoStoreDataSource ) ) { while ( resourceIterator.hasNext() ) { StoreFileMetadata storeFileMetadata = resourceIterator.next(); storeFileStreamingProtocol.stream( ctx, new StoreResource( storeFileMetadata.file(), relativePath( storeDir, storeFileMetadata.file() ), storeFileMetadata.recordSize(), pageCache, fs ) ); } } responseStatus = StoreCopyFinishedResponse.Status.SUCCESS; } } finally { storeFileStreamingProtocol.end( ctx, responseStatus ); protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }</code><technical_language>I need throttle this somehow. a single thread pool is shared for channels avoid spawning multiple threads waiting for a check point complete</technical_language>

Target:
protected void channelRead0( ChannelHandlerContext ctx, T request ) throws Exception { log.debug( "Handling request %s", request ); StoreCopyFinishedResponse.Status responseStatus = StoreCopyFinishedResponse.Status.E_UNKNOWN; try { NeoStoreDataSource neoStoreDataSource = dataSource.get(); if ( !hasSameStoreId( request.expectedStoreId(), neoStoreDataSource ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_STORE_ID_MISMATCH; } else if ( !isTransactionWithinReach( request.requiredTransactionId() ) ) { responseStatus = StoreCopyFinishedResponse.Status.E_TOO_FAR_BEHIND; checkPointerService.tryAsyncCheckpoint( e -> log.error( "Failed to do a checkpoint that was invoked after a too far behind error on store copy request", e ) ); } else { File storeDir = neoStoreDataSource.getStoreDir(); try ( ResourceIterator<StoreFileMetadata> resourceIterator = files( request, neoStoreDataSource ) ) { while ( resourceIterator.hasNext() ) { StoreFileMetadata storeFileMetadata = resourceIterator.next(); storeFileStreamingProtocol.stream( ctx, new StoreResource( storeFileMetadata.file(), relativePath( storeDir, storeFileMetadata.file() ), storeFileMetadata.recordSize(), pageCache, fs ) ); } } responseStatus = StoreCopyFinishedResponse.Status.SUCCESS; } } finally { storeFileStreamingProtocol.end( ctx, responseStatus ); protocol.expect( CatchupServerProtocol.State.MESSAGE_TYPE ); } }
Source:
<code>public String toString() { <START> return String.format("[name=%s, container=%s, uri=%s, bytes=%s, contentType=%s, lastModified=%s, hash=%s]", name, <END> container, uri, bytes, contentType, lastModified, Arrays.toString(hash)); }</code><technical_language>Add objectManifest toString, equals hashCode</technical_language>

Target:
public String toString() { return String.format("[name=%s, container=%s, uri=%s, bytes=%s, contentType=%s, lastModified=%s, hash=%s, objectManifest=%s]", name, container, uri, bytes, contentType, lastModified, Arrays.toString(hash), objectManifest); }
Source:
<code>private boolean evict() { evictionObserver.begin(); Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { evictionObserver.end(EvictionOutcome.SUCCESS); return true; } else { <START> return false; <END> } } }</code><technical_language>observer informed of event either... another outcome constant added</technical_language>

Target:
private boolean evict() { Set<Map.Entry<K, ValueHolder<V>>> values = map.getRandomValues(new Random(), 8, evictionVeto); if (values.isEmpty()) { return false; } else { Map.Entry<K, ValueHolder<V>> evict = Collections.max(values, evictionPrioritizer); if (map.remove(evict.getKey(), evict.getValue())) { return true; } else { return false; } } }
Source:
<code>public void helixInitiatedIdealStateChangeTest() throws Exception { assumeTrue(!useComposite && !overrideEnabled); <START> verifyInitialClusterChanges((HelixClusterManager) clusterManager, helixCluster, dcs); <END> String resourceName = "newResource"; String partitionName = String.valueOf(helixCluster.getAllPartitions().size()); IdealState idealState = new IdealState(resourceName); idealState.setPreferenceList(partitionName, new ArrayList<>()); helixCluster.addNewResource(resourceName, idealState, localDc); verifyInitialClusterChanges((HelixClusterManager) clusterManager, helixCluster, new String[]{localDc}); Map<String, ConcurrentHashMap<String, String>> partitionToResource = ((HelixClusterManager) clusterManager).getPartitionToResourceMap(); assertEquals("localDc should have one more partition", partitionToResource.get(localDc).size(), partitionToResource.get(remoteDc).size() + 1); assertTrue(partitionToResource.get(localDc).containsKey(partitionName) && !partitionToResource.get(remoteDc) .containsKey(partitionName)); }</code><technical_language>Do cast beginning instead of check</technical_language>

Target:
public void helixInitiatedIdealStateChangeTest() throws Exception { assumeTrue(!useComposite && !overrideEnabled); HelixClusterManager helixClusterManager = (HelixClusterManager) clusterManager; verifyInitialClusterChanges(helixClusterManager, helixCluster, dcs); String resourceName = "newResource"; String partitionName = String.valueOf(helixCluster.getAllPartitions().size()); IdealState idealState = new IdealState(resourceName); idealState.setPreferenceList(partitionName, new ArrayList<>()); helixCluster.addNewResource(resourceName, idealState, localDc); verifyInitialClusterChanges(helixClusterManager, helixCluster, new String[]{localDc}); Map<String, ConcurrentHashMap<String, String>> partitionToResource = (helixClusterManager).getPartitionToResourceMap(); assertEquals("localDc should have one more partition", partitionToResource.get(localDc).size(), partitionToResource.get(remoteDc).size() + 1); assertTrue(partitionToResource.get(localDc).containsKey(partitionName) && !partitionToResource.get(remoteDc) .containsKey(partitionName)); }
Source:
<code>private void clusterRestart(boolean withAnotherClient, boolean allowOverwrite) throws Exception { try { startGrid(0); clientMode = true; Ignite client = startGrid(1); if (withAnotherClient) { startGrid(2); stopGrid(2); } clientMode = false; try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k1", "v1"); } stopGrid(0); <START> U.sleep(2_000); <END> startGrid(0); U.sleep(1_000); for (int i = 0; i < 3; i++) { try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k2", "v2"); return; } catch (CacheException ce) { assert ce.getCause() instanceof IgniteClientDisconnectedException; ((IgniteClientDisconnectedException)ce.getCause()).reconnectFuture().get(); } catch (IgniteClientDisconnectedException icde) { icde.reconnectFuture().get(); } } assert false : "Failed to wayt for reconnect!"; } finally { stopAllGrids(); } }</code><technical_language>I suggest rid of Thread.sleep(). reliable. Perhaps, Ignite events do required trick: final CountDownLatch disconnect = new CountDownLatch(1); final CountDownLatch reconnect = new CountDownLatch(1); Ignite client = startGrid(1); client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { reconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_RECONNECTED); client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { disconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_DISCONNECTED); ... stopGrid(0); disconnect.await(); startGrid(0); reconnect.await(); WDYT</technical_language>

Target:
private void clusterRestart(boolean withAnotherClient, boolean allowOverwrite) throws Exception { CountDownLatch disconnect = new CountDownLatch(1); CountDownLatch reconnect = new CountDownLatch(1); try { startGrid(0); clientMode = true; Ignite client = startGrid(1); if (withAnotherClient) { startGrid(2); stopGrid(2); } clientMode = false; try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k1", "v1"); } client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { reconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_RECONNECTED); client.events().localListen(new IgnitePredicate<Event>() { @Override public boolean apply(Event event) { disconnect.countDown(); return false; } }, EventType.EVT_CLIENT_NODE_DISCONNECTED); stopGrid(0); disconnect.await(); startGrid(0); reconnect.await(); try (IgniteDataStreamer<String, String> streamer = client.dataStreamer("test")) { streamer.allowOverwrite(allowOverwrite); streamer.addData("k2", "v2"); return; } } finally { stopAllGrids(); } }
Source:
<code>private void waitMachines( List<CompletableFuture<Void>> machinesFutures, List<CompletableFuture<?>> toCancelFutures, CompletableFuture<Void> failure) throws InfrastructureException, InterruptedException { try { final CompletableFuture<Void> allDone = CompletableFuture.allOf( machinesFutures.toArray(new CompletableFuture[machinesFutures.size()])); <START> CompletableFuture.anyOf(allDone, failure).get(machineStartTimeoutMin, TimeUnit.MINUTES); <END> if (failure.isCompletedExceptionally()) { failure.get(); } } catch (TimeoutException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw new InfrastructureException( "Waiting for Kubernetes environment '" + getContext().getIdentity().getEnvName() + "' of the workspace'" + getContext().getIdentity().getWorkspaceId() + "' reached timeout"); } catch (InterruptedException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw ex; } catch (ExecutionException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); wrapAndRethrow(ex.getCause()); } }</code><technical_language>I understand previously for setting a timeout of waiting for machine running (Pod running installers servers launched yet). this time machines running, installers launched servers RUNNING. Please consider renaming configuration parameter. Kubernetes workspace start timeout</technical_language>

Target:
private void waitMachines( List<CompletableFuture<Void>> machinesFutures, List<CompletableFuture<?>> toCancelFutures, CompletableFuture<Void> failure) throws InfrastructureException, InterruptedException { try { final CompletableFuture<Void> allDone = CompletableFuture.allOf( machinesFutures.toArray(new CompletableFuture[machinesFutures.size()])); CompletableFuture.anyOf(allDone, failure).get(workspaceStartTimeout, TimeUnit.MINUTES); if (failure.isCompletedExceptionally()) { failure.get(); } } catch (TimeoutException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw new InfrastructureException( "Waiting for Kubernetes environment '" + getContext().getIdentity().getEnvName() + "' of the workspace'" + getContext().getIdentity().getWorkspaceId() + "' reached timeout"); } catch (InterruptedException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); throw ex; } catch (ExecutionException ex) { failure.completeExceptionally(ex); cancelAll(toCancelFutures); wrapAndRethrow(ex.getCause()); } }
Source:
<code>public void removeConfigurations(String context) { synchronized (contextMap) { Set<Item> items = contextMap.get(context); if(items!=null) { for(Item item : items) { bindingConfigs.remove(item.getName()); notifyListeners(item); } contextMap.remove(context); <START> } <END> } }</code><technical_language>internal/framework lock held calls, notifyListeners, non-framework code. if bucketed _what_ callout, while framework lock, callouts lock...otherwise, depending locking model of of called entities (Bindings), create a deadlock. PS: want run Eclipse code-formatting function changes align std openHAB uses</technical_language>

Target:
public void removeConfigurations(String context) { Set<Item> items = null; synchronized (contextMap) { items = contextMap.get(context); if (items != null) { contextMap.remove(context); } } if (items != null) { for (Item item : items) { bindingConfigs.remove(item.getName()); notifyListeners(item); } } }
Source:
<code>public synchronized List<List<Object>> getRows(String objectName, List<Integer> selectedColumns) { <START> String lowerCaseTableName = objectName.toLowerCase(); <END> if (!tableData.containsKey(lowerCaseTableName)) { return ImmutableList.of(); } return projectRows(tableData.get(lowerCaseTableName), selectedColumns); }</code><technical_language>rename lowerCaseTableName</technical_language>

Target:
public synchronized List<List<Object>> getRows(String objectName, List<Integer> selectedColumns) { String lowerCaseObjectName = objectName.toLowerCase(); if (!tableData.containsKey(lowerCaseObjectName)) { return ImmutableList.of(); } return projectRows(tableData.get(lowerCaseObjectName), selectedColumns); }
Source:
<code><START> DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { <END> this(morphia, morphia.getMapper(), mongoClient, dbName); }</code><technical_language>implications of breaking binary compatibility here? class of users is this affect? If existing public constructors deprecated removed</technical_language>

Target:
public DatastoreImpl(final Morphia morphia, final MongoClient mongoClient, final String dbName) { this(morphia, morphia.getMapper(), mongoClient, dbName); }
Source:
<code><START> private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) throws InvalidWebSocketException <END> { return MethodHandles.publicLookup().in(endpointClass); }</code><technical_language>remove throws InvalidWebSocketException now</technical_language>

Target:
private MethodHandles.Lookup getMethodHandleLookup(Class<?> endpointClass) { return MethodHandles.publicLookup().in(endpointClass); }
Source:
<code>public List<SampleList> getByParentFolderId(final Integer parentId, final String programUUID) { try { if (parentId != null) { final Criteria criteria = this.getSession().createCriteria(SampleList.class); criteria.add(Restrictions.eq("hierarchy.id", parentId)); criteria.add(Restrictions.eq(SampleListDao.PROGRAMUUID, programUUID)); criteria.addOrder(Order.asc(SampleListDao.LIST_NAME)); return criteria.list(); } } catch (final HibernateException e) { <START> this.logAndThrowException("Error with getByParentFolderId(parentId=" + parentId + ") query from SampleList: " + e.getMessage(), <END> e); } return new ArrayList<>(); }</code><technical_language>@cuenyad Replace logAndThrow</technical_language>

Target:
public List<SampleList> getByParentFolderId(final Integer parentId, final String programUUID) { try { if (parentId != null) { final Criteria criteria = this.getSession().createCriteria(SampleList.class); criteria.add(Restrictions.eq("hierarchy.id", parentId)); criteria.add(Restrictions.eq(SampleListDao.PROGRAMUUID, programUUID)); criteria.addOrder(Order.asc(SampleListDao.LIST_NAME)); return criteria.list(); } } catch (final HibernateException e) { throw new MiddlewareQueryException("Error with getByParentFolderId(parentId=" + parentId + ") query from SampleList: " + e.getMessage(), e); } return new ArrayList<>(); }
Source:
<code>private boolean advance() { TSource left = leftEnumerator.current(); TKey leftKey = outerKeySelector.apply(left); TInner right = rightEnumerator.current(); TKey rightKey = innerKeySelector.apply(right); for (;;) { int c = leftKey.compareTo(rightKey); if (c == 0) { break; } if (c < 0) { if (!leftEnumerator.moveNext()) { done = true; return false; } left = leftEnumerator.current(); leftKey = outerKeySelector.apply(left); } else { if (!rightEnumerator.moveNext()) { done = true; return false; } right = rightEnumerator.current(); rightKey = innerKeySelector.apply(right); } } lefts.clear(); lefts.add(left); for (;;) { if (!leftEnumerator.moveNext()) { done = true; break; } left = leftEnumerator.current(); TKey leftKey2 = outerKeySelector.apply(left); int c = leftKey.compareTo(leftKey2); if (c != 0) { <START> if (c < 0) { <END> throw new IllegalStateException( "not sorted, " + leftKey + " is less than " + leftKey2); } break; } lefts.add(left); } rights.clear(); rights.add(right); for (;;) { if (!rightEnumerator.moveNext()) { done = true; break; } right = rightEnumerator.current(); TKey rightKey2 = innerKeySelector.apply(right); int c = rightKey.compareTo(rightKey2); if (c != 0) { if (c < 0) { throw new IllegalStateException( "not sorted, " + rightKey + " is less than " + rightKey2); } break; } rights.add(right); } cartesians = Linq4j.product( ImmutableList.of(Linq4j.enumerator(lefts), Linq4j.enumerator(rights))); return true; }</code><technical_language>condition c > 0. Original assertion c<0==true, assertion is violated in c>0 case</technical_language>

Target:
private boolean advance() { TSource left = leftEnumerator.current(); TKey leftKey = outerKeySelector.apply(left); TInner right = rightEnumerator.current(); TKey rightKey = innerKeySelector.apply(right); for (;;) { int c = leftKey.compareTo(rightKey); if (c == 0) { break; } if (c < 0) { if (!leftEnumerator.moveNext()) { done = true; return false; } left = leftEnumerator.current(); leftKey = outerKeySelector.apply(left); } else { if (!rightEnumerator.moveNext()) { done = true; return false; } right = rightEnumerator.current(); rightKey = innerKeySelector.apply(right); } } lefts.clear(); lefts.add(left); for (;;) { if (!leftEnumerator.moveNext()) { done = true; break; } left = leftEnumerator.current(); TKey leftKey2 = outerKeySelector.apply(left); int c = leftKey.compareTo(leftKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes inputs sorted in ascending order, " + "however " + leftKey + " is greater than " + leftKey2); } break; } lefts.add(left); } rights.clear(); rights.add(right); for (;;) { if (!rightEnumerator.moveNext()) { done = true; break; } right = rightEnumerator.current(); TKey rightKey2 = innerKeySelector.apply(right); int c = rightKey.compareTo(rightKey2); if (c != 0) { if (c > 0) { throw new IllegalStateException( "mergeJoin assumes input sorted in ascending order, " + "however " + rightKey + " is greater than " + rightKey2); } break; } rights.add(right); } cartesians = Linq4j.product( ImmutableList.of(Linq4j.enumerator(lefts), Linq4j.enumerator(rights))); return true; }
Source:
<code>public void fetchAllMenus() { String path = formatPath(MENUS_REST_PATH, null); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { JSONArray menusJson = response.optJSONArray(ALL_MENUS_MENUS_KEY); List<MenuModel> menus = new ArrayList<>(); try { for (int i = 0; i < menusJson.length(); ++i) { menus.add(menuFromJson(menusJson.getJSONObject(i))); } } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error parsing All Menus REST response"); } <START> mDelegate.onMenusReceived(HttpURLConnection.HTTP_OK, menus); <END> } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { mDelegate.onMenusReceived(statusCodeFromVolleyError(error), null); } }); }</code><technical_language>Idea for improvement/discussion: delegate simplified generalising onMenusReceived, in specific case of fetching element return ArrayListcontainting 1 element instead of delegates? (I'm referring onMenuReceived onMenusRecevied). generally good way, check in terms of separation vs. easiness of implementation. I forced map WP REST API entirely, _could_ consumer of this class's life easier if want</technical_language>

Target:
public int fetchAllMenus() { final int requestId = ++mRequestCounter; String path = formatPath(MENUS_REST_PATH, null); Map<String, String> params = new HashMap<>(); WordPress.getRestClientUtilsV1_1().get(path, params, null, new RestRequest.Listener() { @Override public void onResponse(JSONObject response) { JSONArray menusJson = response.optJSONArray(ALL_MENUS_MENUS_KEY); List<MenuModel> menus = new ArrayList<>(); try { for (int i = 0; i < menusJson.length(); ++i) { menus.add(menuFromJson(menusJson.getJSONObject(i))); } } catch (JSONException exception) { AppLog.w(AppLog.T.API, "Error parsing All Menus REST response"); } mListener.onMenusReceived(requestId, menus); } }, new RestRequest.ErrorListener() { @Override public void onErrorResponse(VolleyError volleyError) { int statusCode = statusCodeFromVolleyError(volleyError); REST_ERROR error = REST_ERROR.FETCH_ERROR; if (statusCode == HTTP_FORBIDDEN) error = REST_ERROR.AUTHENTICATION_ERROR; mListener.onErrorResponse(requestId, error); } }); return requestId; }
Source:
<code>private Pair<Authentication, Boolean> getOnBehalfOfAuthentication(Context context, String onBehalfOfParameterValue, HttpServletResponse res) throws IOException { try { if (!authorizeService.isAdmin(context)) { res.sendError(HttpServletResponse.SC_FORBIDDEN, "Only admins are allowed to use the" + " login as feature"); return Pair.of(null, true); } UUID epersonUuid = UUIDUtils.fromString(onBehalfOfParameterValue); if (epersonUuid == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "The given UUID in the X-On-Behalf-Of header " + "was not a proper UUID"); return Pair.of(null, true); } EPerson onBehalfOfEPerson = ePersonService.find(context, epersonUuid); if (onBehalfOfEPerson == null) { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "The given UUID in the X-On-Behalf-Of header " + "was not a proper EPerson UUID"); return Pair.of(null, true); } if (!authorizeService.isAdmin(context, onBehalfOfEPerson)) { requestService.setCurrentUserId(epersonUuid); context.switchContextUser(onBehalfOfEPerson); return Pair.of(new DSpaceAuthentication(onBehalfOfEPerson.getEmail(), authenticationProvider.getGrantedAuthorities(context, onBehalfOfEPerson)), false); } else { res.sendError(HttpServletResponse.SC_BAD_REQUEST, "You're unable to use the login as feature to log " + "in as another admin"); return Pair.of(null, true); } } catch (SQLException e) { log.error(e.getMessage(), e); <START> return Pair.of(null, false); <END> } }</code><technical_language>This a bit odd me. return error error occurred? This essentially a no-op if a SQLException (or I missing something)</technical_language>

Target:
private Authentication getOnBehalfOfAuthentication(Context context, String onBehalfOfParameterValue, HttpServletResponse res) throws SQLException { if (!authorizeService.isAdmin(context)) { throw new AccessDeniedException("Only admins are allowed to use the login as feature"); } UUID epersonUuid = UUIDUtils.fromString(onBehalfOfParameterValue); if (epersonUuid == null) { throw new IllegalArgumentException("The given UUID in the X-On-Behalf-Of header " + "was not a proper UUID"); } EPerson onBehalfOfEPerson = ePersonService.find(context, epersonUuid); if (onBehalfOfEPerson == null) { throw new IllegalArgumentException("The given UUID in the X-On-Behalf-Of header " + "was not a proper EPerson UUID"); } if (!authorizeService.isAdmin(context, onBehalfOfEPerson)) { requestService.setCurrentUserId(epersonUuid); context.switchContextUser(onBehalfOfEPerson); return new DSpaceAuthentication(onBehalfOfEPerson.getEmail(), authenticationProvider.getGrantedAuthorities(context, onBehalfOfEPerson)); } else { throw new IllegalArgumentException("You're unable to use the login as feature to log " + "in as another admin"); } }
Source:
<code>public StudentAttributes makeStudent(String enrollLine, String courseId) throws EnrollException { if (enrollLine.isEmpty()) { throw new EnrollException(ERROR_ENROLL_LINE_EMPTY); } String[] columns = splitLineIntoColumns(enrollLine); boolean hasMissingFields = columns.length <= teamColumnIndex || columns.length <= nameColumnIndex || columns.length <= emailColumnIndex; if (hasMissingFields) { throw new EnrollException(ERROR_ENROLL_LINE_TOOFEWPARTS); } String paramTeam = StringHelper.removeExtraSpace(columns[teamColumnIndex]); String paramName = StringHelper.removeExtraSpace(columns[nameColumnIndex]); String paramEmail = StringHelper.removeExtraSpace(columns[emailColumnIndex]); String paramComment = ""; if (hasComment && columns.length > commentColumnIndex) { paramComment = StringHelper.removeExtraSpace(columns[commentColumnIndex]); } String paramSection; if (columns[sectionColumnIndex].isEmpty()) { hasSection = false; } <START> <END> if (hasSection && columns.length > sectionColumnIndex) { paramSection = StringHelper.removeExtraSpace(columns[sectionColumnIndex]); } else { paramSection = Const.DEFAULT_SECTION; } return StudentAttributes .builder(courseId, paramName, paramEmail) .withTeam(paramTeam) .withSection(paramSection) .withComments(paramComment) .build(); }</code><technical_language>I this approach, I has... variables purely reflect status of header row. add a && !columns[sectionColumnIndex].isEmpty() check below</technical_language>

Target:
public StudentAttributes makeStudent(String enrollLine, String courseId) throws EnrollException { if (enrollLine.isEmpty()) { throw new EnrollException(ERROR_ENROLL_LINE_EMPTY); } String[] columns = splitLineIntoColumns(enrollLine); boolean hasMissingFields = columns.length <= teamColumnIndex || columns.length <= nameColumnIndex || columns.length <= emailColumnIndex; if (hasMissingFields) { throw new EnrollException(ERROR_ENROLL_LINE_TOOFEWPARTS); } String paramTeam = StringHelper.removeExtraSpace(columns[teamColumnIndex]); String paramName = StringHelper.removeExtraSpace(columns[nameColumnIndex]); String paramEmail = StringHelper.removeExtraSpace(columns[emailColumnIndex]); String paramComment = ""; if (hasComment && columns.length > commentColumnIndex) { paramComment = StringHelper.removeExtraSpace(columns[commentColumnIndex]); } String paramSection; if (hasSection && columns.length > sectionColumnIndex && !columns[sectionColumnIndex].isEmpty()) { paramSection = StringHelper.removeExtraSpace(columns[sectionColumnIndex]); } else { paramSection = Const.DEFAULT_SECTION; } return StudentAttributes .builder(courseId, paramName, paramEmail) .withTeam(paramTeam) .withSection(paramSection) .withComments(paramComment) .build(); }
Source:
<code>private Process postProcess(Process process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } try { final Process result = restTemplate.postForObject(postUri, parts, Process.class); <START> deleteTempFile(tempFile); <END> return result; } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create dataload process.", e); } }</code><technical_language>this part of some finally block</technical_language>

Target:
private Process postProcess(Process process, File processData, URI postUri) { File tempFile = createTempFile("process", ".zip"); final MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>(2); parts.add("process", process); final HttpHeaders headers = new HttpHeaders(); headers.setContentType(MEDIA_TYPE_ZIP); parts.add("data", new HttpEntity<>(new FileSystemResource(tempFile), headers)); try (FileOutputStream output = new FileOutputStream(tempFile)) { ZipUtils.zip(processData, output); } catch (IOException e) { throw new GoodDataException("Unable to zip process data", e); } try { return restTemplate.postForObject(postUri, parts, Process.class); } catch (GoodDataException | RestClientException e) { throw new GoodDataException("Unable to create dataload process.", e); } finally { deleteTempFile(tempFile); } }
Source:
<code>protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK) { Intent intent = new Intent(ProductActivity.this, AddProductActivity.class); intent.putExtra("edit_product", mState.getProduct()); startActivityForResult(intent, EDIT_REQUEST_CODE); } if (requestCode == EDIT_REQUEST_CODE && resultCode == RESULT_OK) { <START> api.getProduct(mState.getProduct().getCode(), this); <END> } }</code><technical_language>onRefresh() instead</technical_language>

Target:
protected void onActivityResult( int requestCode, int resultCode, Intent data ) { super.onActivityResult( requestCode, resultCode, data ); if( requestCode == LOGIN_ACTIVITY_REQUEST_CODE && resultCode == RESULT_OK ) { Intent intent = new Intent( ProductActivity.this, AddProductActivity.class ); intent.putExtra( "edit_product", mState.getProduct() ); startActivity( intent ); } if( requestCode == EDIT_REQUEST_CODE && resultCode == RESULT_OK) { onRefresh(); } }
Source:
<code>private KernelTransactionImplementation createTransaction() { KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class ); try { TransactionHeaderInformation headerInformation = new TransactionHeaderInformation( -1, -1, new byte[0] ); TransactionHeaderInformationFactory headerInformationFactory = mock( TransactionHeaderInformationFactory.class ); when( headerInformationFactory.create() ).thenReturn( headerInformation ); StorageEngine storageEngine = mock( StorageEngine.class ); StoreReadLayer storeReadLayer = mock( StoreReadLayer.class ); StorageStatement storageStatement = mock( StorageStatement.class ); when( storeReadLayer.newStatement() ).thenReturn( storageStatement ); when( storageEngine.storeReadLayer() ).thenReturn( storeReadLayer ); SimpleStatementLocks locks = new SimpleStatementLocks( mock( org.neo4j.kernel.impl.locking.Locks.Client.class ) ); when( transaction.statementLocks() ).thenReturn( locks ); when( transaction.tokenRead() ).thenReturn( tokenRead ); when( transaction.schemaRead() ).thenReturn( schemaRead ); when( transaction.schemaWrite() ).thenReturn( schemaWrite ); TransactionState transactionState = mock( TransactionState.class ); when( transaction.txState() ).thenReturn( transactionState ); when( transaction.indexUniqueCreate( any( SchemaDescriptor.class ), any( Optional.class ) ) ).thenAnswer( i -> IndexDescriptorFactory.uniqueForSchema( i.getArgument( 0 ) ) ); } catch ( InvalidTransactionTypeKernelException e ) { <START> e.printStackTrace(); <END> } return transaction; }</code><technical_language>Oops</technical_language>

Target:
private KernelTransactionImplementation createTransaction() { KernelTransactionImplementation transaction = mock( KernelTransactionImplementation.class ); try { TransactionHeaderInformation headerInformation = new TransactionHeaderInformation( -1, -1, new byte[0] ); TransactionHeaderInformationFactory headerInformationFactory = mock( TransactionHeaderInformationFactory.class ); when( headerInformationFactory.create() ).thenReturn( headerInformation ); StorageEngine storageEngine = mock( StorageEngine.class ); StorageReader storageReader = mock( StorageReader.class ); when( storageEngine.newReader() ).thenReturn( storageReader ); SimpleStatementLocks locks = new SimpleStatementLocks( mock( org.neo4j.kernel.impl.locking.Locks.Client.class ) ); when( transaction.statementLocks() ).thenReturn( locks ); when( transaction.tokenRead() ).thenReturn( tokenRead ); when( transaction.schemaRead() ).thenReturn( schemaRead ); when( transaction.schemaWrite() ).thenReturn( schemaWrite ); TransactionState transactionState = mock( TransactionState.class ); when( transaction.txState() ).thenReturn( transactionState ); when( transaction.indexUniqueCreate( any( SchemaDescriptor.class ), any( Optional.class ) ) ).thenAnswer( i -> IndexDescriptorFactory.uniqueForSchema( i.getArgument( 0 ) ) ); } catch ( InvalidTransactionTypeKernelException e ) { fail( "Expected write transaction" ); } return transaction; }
Source:
<code>private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate localCosts = costCalculator.calculateCost(node, statsProvider, noLookup(), session, types); PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); <START> PlanNodeCostEstimate cumulativeCost = localCosts.add(sourcesCost); <END> return cumulativeCost; }</code><technical_language>Inline</technical_language>

Target:
private PlanNodeCostEstimate calculateCumulativeCost(PlanNode node) { PlanNodeCostEstimate sourcesCost = node.getSources().stream() .map(this::getCumulativeCost) .reduce(ZERO_COST, PlanNodeCostEstimate::add); return costCalculator.calculateCost(node, statsProvider, session, types).add(sourcesCost); }
Source:
<code>private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = null; if (operatedAccount != null) operatedAccountSid = operatedAccount.getSid().toString(); <START> if (isSuperAdmin()) { <END> return AuthOutcome.OK; } if (resourceAccountSid != null) if (! resourceAccountSid.equals(operatedAccountSid)) return AuthOutcome.FAILED; if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; if ( operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid)) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; }</code><technical_language>this affect other existing operations? a big change.... Of this means is superAdmin anyway, wanted check if this change for other existing RESTAPI operations..</technical_language>

Target:
private AuthOutcome secureLevelControl(Account operatedAccount, String resourceAccountSid) { Account operatingAccount = userIdentityContext.getEffectiveAccount(); String operatingAccountSid = null; if (operatingAccount != null) operatingAccountSid = operatingAccount.getSid().toString(); String operatedAccountSid = null; if (operatedAccount != null) operatedAccountSid = operatedAccount.getSid().toString(); if (resourceAccountSid != null) if (! resourceAccountSid.equals(operatedAccountSid)) return AuthOutcome.FAILED; if ( operatingAccountSid.equals(operatedAccountSid) ) return AuthOutcome.OK; if ( operatedAccount.getParentSid() != null ) { if (operatedAccount.getParentSid().toString().equals(operatingAccountSid)) return AuthOutcome.OK; else if (accountsDao.getAccountLineage(operatedAccount).contains(operatingAccountSid)) return AuthOutcome.OK; } return AuthOutcome.FAILED; }
Source:
<code>private void writeVcf(final SortingCollection<VariantContext> variants, final File output, final SAMSequenceDictionary dict, final VCFHeader vcfHeader) { <START> final VariantContextWriter writer = new VariantContextWriterBuilder() <END> .setOutputFile(output) .setReferenceDictionary(dict) .setOptions(VariantContextWriterBuilder.DEFAULT_OPTIONS) .build(); writer.writeHeader(vcfHeader); for (final VariantContext variant : variants) { if (variant.getAlternateAlleles().size() > 1) { variant.getCommonInfo().addFilter(InfiniumVcfFields.TRIALLELIC); } writer.add(variant); } writer.close(); }</code><technical_language>TWR close</technical_language>

Target:
private void writeVcf(final SortingCollection<VariantContext> variants, final File output, final SAMSequenceDictionary dict, final VCFHeader vcfHeader) { try (final VariantContextWriter writer = new VariantContextWriterBuilder() .setOutputFile(output) .setReferenceDictionary(dict) .setOptions(VariantContextWriterBuilder.DEFAULT_OPTIONS) .build()) { writer.writeHeader(vcfHeader); for (final VariantContext variant : variants) { if (variant.getAlternateAlleles().size() > 1) { variant.getCommonInfo().addFilter(InfiniumVcfFields.TRIALLELIC); } writer.add(variant); } } }
Source:
<code>public void produced(long n) { if (n <= 0) { throw new IllegalArgumentException("n > 0 required"); } synchronized (this) { if (emitting) { missedProduced += n; return; } emitting = true; } boolean skipFinal = false; try { long r = requested; <START> long u = r - n; <END> if (u < 0) { throw new IllegalStateException(); } requested = u; emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }</code><technical_language>reduce requested if Long.MAX_VALUE</technical_language>

Target:
public void produced(long n) { if (n <= 0) { throw new IllegalArgumentException("n > 0 required"); } synchronized (this) { if (emitting) { missedProduced += n; return; } emitting = true; } boolean skipFinal = false; try { long r = requested; if (r != Long.MAX_VALUE) { long u = r - n; if (u < 0) { throw new IllegalStateException(); } requested = u; } emitLoop(); skipFinal = true; } finally { if (!skipFinal) { synchronized (this) { emitting = false; } } } }
Source:
<code>public void testConvertEnums() throws IOException{ String enumName = "FakeEnum"; String enumValue1 = "FakeEnumValue1"; String enumValue2 = "FakeEnumValue2"; Enum e = new Enum(enumName); e.setValues(new HashSet<EnumValue>(Arrays.asList( new EnumValue(enumName, enumValue1, null), new EnumValue(enumName, enumValue2, null)))); Enums enums = new Enums(); enums.addEnum(e); JsonNode enumsNode = json("{}"); parser.convertEnums(enumsNode, enums); <START> String jsonString = enumsNode.toString(); <END> Assert.assertTrue(jsonString.contains("enums")); Assert.assertTrue(jsonString.contains(enumName)); Assert.assertTrue(jsonString.matches(".*\"values\":\\[.*")); Assert.assertFalse(jsonString.matches(".*\"annotatedValues\":\\[.*")); Assert.assertTrue(jsonString.contains(enumValue1)); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue1 + "\"")); Assert.assertTrue(jsonString.contains(enumValue2)); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue2 + "\"")); }</code><technical_language>For json verification org.skyscreamer.jsonassert.JSONAssert</technical_language>

Target:
public void testConvertEnums() throws IOException, JSONException{ String enumName = "FakeEnum"; String enumValue1 = "FakeEnumValue1"; String enumValue2 = "FakeEnumValue2"; Enum e = new Enum(enumName); e.setValues(new HashSet<EnumValue>(Arrays.asList( new EnumValue(enumValue1, null), new EnumValue(enumValue2, null)))); Enums enums = new Enums(); enums.addEnum(e); JsonNode enumsNode = json("{}"); parser.convertEnums(enumsNode, enums); String jsonString = enumsNode.toString(); JSONAssert.assertEquals("{enums:[{name:\"" + enumName + "\",values:[\"" + enumValue1 + "\",\"" + enumValue2 + "\"]}]}", jsonString, false); Assert.assertFalse(jsonString.matches(".*\"annotatedValues\":\\[.*")); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue1 + "\"")); Assert.assertFalse(jsonString.contains("\"name\":\"" + enumValue2 + "\"")); }
Source:
<code>public void testRangeOption() throws Exception { ByteRange range = ByteRange.fromOffsetRange(1, 2); GetBlobOptions options = new GetBlobOptions(range); <START> assertEquals(range, options.getRange()); <END> }</code><technical_language>A message helpful</technical_language>

Target:
public void testRangeOption() throws Exception { long startOffset = 1; long endOffset = 2; ByteRange range = ByteRange.fromOffsetRange(startOffset, endOffset); GetBlobOptions options = new GetBlobOptions(ByteRange.fromOffsetRange(startOffset, endOffset)); assertEquals("Range from options not as expected.", range, options.getRange()); }