auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code><START> public Page<TaskState> getTaskStates(String taskTag, long from, long to, boolean mytasks, <END> boolean running, boolean pending, boolean finished, int offset, int limit, SortSpecifierContainer sortParams) throws NotConnectedException, PermissionException { RestPage<TaskStateData> page = null; SortSpecifierRestContainer sortContainer = new SortSpecifierRestContainer(sortParams.toString()); try { page = restApi().getTaskStates(sid, from, to, mytasks, running, pending, finished, offset, limit, sortContainer); } catch (NotConnectedRestException e) { throw new NotConnectedException(e); } catch (PermissionRestException e) { throw new PermissionException(e); } List<TaskState> lTaskStates = new ArrayList<TaskState>(page.getList().size()); for (TaskStateData taskStateData : page.getList()) { lTaskStates.add(new TaskStateImpl(taskStateData)); } return new Page<TaskState>(lTaskStates, page.getSize()); }</code><technical_language>![MAJOR](<LINK_0> Method 10 parameters, is greater 7 authorized. [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
public Page<TaskState> getTaskStates(String taskTag, long from, long to, boolean mytasks, boolean running, boolean pending, boolean finished, int offset, int limit, SortSpecifierContainer sortParams) throws NotConnectedException, PermissionException { RestPage<TaskStateData> page = null; SortSpecifierContainer sortContainer = new SortSpecifierContainer(sortParams.toString()); try { page = restApi().getTaskStates(sid, from, to, mytasks, running, pending, finished, offset, limit, sortContainer); } catch (NotConnectedRestException e) { throw new NotConnectedException(e); } catch (PermissionRestException e) { throw new PermissionException(e); } List<TaskState> lTaskStates = new ArrayList<TaskState>(page.getList().size()); for (TaskStateData taskStateData : page.getList()) { lTaskStates.add(new TaskStateImpl(taskStateData)); } return new Page<TaskState>(lTaskStates, page.getSize()); }
Source:
<code>public static void deployArtifacts() { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/cloudbalance").getFile()); kieContainer = KieServices.Factory.get().newKieContainer(kjar1); KieServicesClient client = createDefaultStaticClient(EXTENDED_TIMEOUT); ServiceResponse<KieContainerResource> reply = client.createContainer(CONTAINER_1_ID, new KieContainerResource(CONTAINER_1_ID, kjar1)); <START> Assume.assumeTrue(reply.getType().equals(ServiceResponse.ResponseType.SUCCESS)); <END> }</code><technical_language>Is assume want (as opposed assert)? This silently skip tests in case condition is satisfied</technical_language>

Target:
public static void deployArtifacts() { KieServerDeployer.buildAndDeployCommonMavenParent(); KieServerDeployer.buildAndDeployMavenProject(ClassLoader.class.getResource("/kjars-sources/cloudbalance").getFile()); kieContainer = KieServices.Factory.get().newKieContainer(kjar1); KieServicesClient client = createDefaultStaticClient(EXTENDED_TIMEOUT); ServiceResponse<KieContainerResource> reply = client.createContainer(CONTAINER_1_ID, new KieContainerResource(CONTAINER_1_ID, kjar1)); KieServerAssert.assertSuccess(reply); }
Source:
<code>private LocationEntity createDemoLocationEntity(Long id, String uuid, String name, String description, String display) { LocationEntity entity = new LocationEntity(""); <START> entity.setId(id); <END> entity.setDisplay(display); entity.setUuid(uuid); entity.setName(name); entity.setDescription(description); entity.setAddress_1("address 1"); entity.setAddress_2("address2"); entity.setCity("city"); entity.setState("state"); entity.setCountry("country"); entity.setPostalCode("postal code"); entity.setParentLocationuuid("location"); return entity; }</code><technical_language>@rishabh-997 is in application constants convers this</technical_language>

Target:
private LocationEntity createDemoLocationEntity(Long id, String uuid, String name, String description, String display) { LocationEntity entity = new LocationEntity(ApplicationConstants.EMPTY_STRING); entity.setId(id); entity.setDisplay(display); entity.setUuid(uuid); entity.setName(name); entity.setDescription(description); entity.setAddress_1("address 1"); entity.setAddress_2("address2"); entity.setCity("city"); entity.setState("state"); entity.setCountry("country"); entity.setPostalCode("postal code"); entity.setParentLocationuuid("location"); return entity; }
Source:
<code>public void onNext(final Message<ShuffleControlMessage> message) { final ShuffleControlMessage controlMessage = message.getData().iterator().next(); final String endPointId = message.getSrcId().toString(); switch (controlMessage.getCode()) { case PushShuffleCode.SENDER_INITIALIZED: stateManager.onSenderInitialized(endPointId); break; case PushShuffleCode.SENDER_FINISHED: stateManager.onSenderFinished(endPointId); break; case PushShuffleCode.RECEIVER_INITIALIZED: stateManager.onReceiverInitialized(endPointId); break; case PushShuffleCode.RECEIVER_COMPLETED: stateManager.onReceiverCompleted(endPointId); break; <START> case PushShuffleCode.RECEIVER_READY: <END> stateManager.onReceiverReady(endPointId); break; case PushShuffleCode.RECEIVER_FINISHED: stateManager.onReceiverFinished(endPointId); break; default: throw new IllegalStateException("Unknown code " + controlMessage.getCode() + " from " + endPointId); } }</code><technical_language>change name of code method RECEIVER_READIED</technical_language>

Target:
public void onNext(final Message<ShuffleControlMessage> message) { final ShuffleControlMessage controlMessage = message.getData().iterator().next(); final String endPointId = message.getSrcId().toString(); switch (controlMessage.getCode()) { case PushShuffleCode.SENDER_INITIALIZED: stateManager.onSenderInitialized(endPointId); break; case PushShuffleCode.SENDER_FINISHED: stateManager.onSenderFinished(endPointId); break; case PushShuffleCode.RECEIVER_INITIALIZED: stateManager.onReceiverInitialized(endPointId); break; case PushShuffleCode.RECEIVER_COMPLETED: stateManager.onReceiverCompleted(endPointId); break; case PushShuffleCode.RECEIVER_READIED: stateManager.onReceiverReadied(endPointId); break; case PushShuffleCode.RECEIVER_FINISHED: stateManager.onReceiverFinished(endPointId); break; default: throw new IllegalStateException("Unknown code " + controlMessage.getCode() + " from " + endPointId); } }
Source:
<code>private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() <START> .relativize(source.getTarget()) <END> .toString(); String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); RepositoryPath target = targetBase.resolve(sTargetPath); return target; }</code><technical_language>![CRITICAL](<LINK_0> null pointer dereference in org.carlspring.strongbox.io.RepositoryFileSystemProvider.rebase(RepositoryPath, RepositoryPath) due return of called method [![rule](<LINK_1>](<LINK_2></technical_language>

Target:
private static RepositoryPath rebase(RepositoryPath source, RepositoryPath targetBase) { FileSystem sourceFileSystem = source.getTarget().getFileSystem(); FileSystem targetFileSystem = targetBase.getTarget().getFileSystem(); String sourceRelative = source.getRoot() .relativize(source.getTarget()) .toString(); String sTargetPath = sourceRelative.replaceAll(sourceFileSystem.getSeparator(), targetFileSystem.getSeparator()); return targetBase.resolve(sTargetPath); }
Source:
<code>@Override public ClientResponse process(ClientConnectionContext ctx) { ClientComputeTask task = new ClientComputeTask(ctx); ctx.incrementActiveTasksCount(); long taskId = ctx.resources().put(task); try { Object arg0 = arg; <START> if ((flags & ClientComputeTask.KEEP_BINARY_FLAG_MASK) == 0 && arg instanceof BinaryObject) { <END> arg0 = ((BinaryObject)arg).deserialize(); } task.execute(taskId, taskName, arg0, nodeIds, flags, timeout); } catch (Exception e) { ctx.resources().release(taskId); throw e; } return new ClientExecuteTaskResponse(requestId(), task); }</code><technical_language>Redundant { } for line statement (codestyle)</technical_language>

Target:
@Override public ClientResponse process(ClientConnectionContext ctx) { ClientComputeTask task = new ClientComputeTask(ctx); ctx.incrementActiveTasksCount(); long taskId = ctx.resources().put(task); try { Object arg0 = arg; if ((flags & ClientComputeTask.KEEP_BINARY_FLAG_MASK) == 0 && arg instanceof BinaryObject) arg0 = ((BinaryObject) arg).deserialize(); task.execute(taskId, taskName, arg0, nodeIds, flags, timeout); } catch (Exception e) { ctx.resources().release(taskId); throw e; } return new ClientExecuteTaskResponse(requestId(), task); }
Source:
<code>public FarObject toFarObject() { FarObject farObject = new FarObject() { @Override public boolean shouldBeRemoved(SolGame game) { return false; } @Override public SolObject toObject(SolGame game) { for(Waypoint waypoint : game.getHero().getWaypoints()) if(waypoint.position.x == position.x && waypoint.position.y == position.y) return waypoint; <START> System.out.println("RETURNDED NUL L"); <END> return null; } @Override public void update(SolGame game) { } @Override public float getRadius() { return 0; } @Override public Vector2 getPosition() { return position; } @Override public String toDebugString() { return "Waypoint"; } @Override public boolean hasBody() { return false; } }; return farObject; }</code><technical_language>I doubt this intended here</technical_language>

Target:
public FarObject toFarObject() { FarObject farObject = new FarObject() { @Override public boolean shouldBeRemoved(SolGame game) { return false; } @Override public SolObject toObject(SolGame game) { for (Waypoint waypoint : game.getHero().getWaypoints()) if (waypoint.position.equals(position)) { return waypoint; } return null; } @Override public void update(SolGame game) { } @Override public float getRadius() { return 0; } @Override public Vector2 getPosition() { return position; } @Override public String toDebugString() { return "Waypoint"; } @Override public boolean hasBody() { return false; } }; return farObject; }
Source:
<code>public void buildGraph( Graph graph, HashMap<Class<?>, Object> extra, DataImportIssueStore issueStore ) { LOG.info("Linking transit stops to tagged bus stops..."); index = new StreetVertexIndex(graph); ArrayList<Vertex> vertices = new ArrayList<>(); vertices.addAll(graph.getVertices()); for (TransitStopVertex ts : Iterables.filter(vertices, TransitStopVertex.class)) { boolean alreadyLinked = false; for(Edge e:ts.getOutgoing()){ if(e instanceof StreetTransitLink) { alreadyLinked = true; break; } } if(alreadyLinked) continue; <START> if (!ts.isStreetLinkable()) { <END> boolean wheelchairAccessible = ts.hasWheelchairEntrance(); if (!connectVertexToStop(ts, wheelchairAccessible)) { LOG.debug("Could not connect " + ts.getStop().getCode() + " at " + ts.getCoordinate().toString()); } } } }</code><technical_language>Rename method "hasPathways", is clearer avoids negation</technical_language>

Target:
public void buildGraph( Graph graph, HashMap<Class<?>, Object> extra, DataImportIssueStore issueStore ) { LOG.info("Linking transit stops to tagged bus stops..."); index = new StreetVertexIndex(graph); ArrayList<Vertex> vertices = new ArrayList<>(); vertices.addAll(graph.getVertices()); for (TransitStopVertex ts : Iterables.filter(vertices, TransitStopVertex.class)) { boolean alreadyLinked = false; for(Edge e:ts.getOutgoing()){ if(e instanceof StreetTransitLink) { alreadyLinked = true; break; } } if(alreadyLinked) continue; if (!ts.hasPathways()) { boolean wheelchairAccessible = ts.hasWheelchairEntrance(); if (!connectVertexToStop(ts, wheelchairAccessible)) { LOG.debug("Could not connect " + ts.getStop().getCode() + " at " + ts.getCoordinate().toString()); } } } }
Source:
<code>public void doAction() throws Exception { logger.info("ready to do action " + getDescription()); <START> FlowRunnerManager flowRunnerManager = ServiceProvider.SERVICE_PROVIDER.getInstance(FlowRunnerManager.class); <END> flowRunnerManager.cancelJobBySLA(execId, jobId); }</code><technical_language>flowRunnerManager initialized in body of constructor</technical_language>

Target:
public void doAction() throws Exception { logger.info("ready to do action " + getDescription()); final FlowRunnerManager flowRunnerManager = ServiceProvider.SERVICE_PROVIDER .getInstance(FlowRunnerManager.class); flowRunnerManager.cancelJobBySLA(this.execId, this.jobId); }
Source:
<code>static void checkType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Boolean || obj instanceof Double || obj instanceof Float || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj instanceof byte[] || <START> obj instanceof JsonObject || <END> obj instanceof JsonArray || obj instanceof Shareable) { } else { throw new IllegalArgumentException("Invalid type for shareddata data structure: " + obj.getClass().getName()); } }</code><technical_language>I if JsonObject JsonArray implement it, need remove this list</technical_language>

Target:
static void checkType(Object obj) { if (obj instanceof String || obj instanceof Integer || obj instanceof Long || obj instanceof Boolean || obj instanceof Double || obj instanceof Float || obj instanceof Short || obj instanceof Byte || obj instanceof Character || obj instanceof byte[] || obj instanceof Shareable) { } else { throw new IllegalArgumentException("Invalid type for shareddata data structure: " + obj.getClass().getName()); } }
Source:
<code>public TypedValue getTypedValue(boolean deserializeValue, boolean asTransientValue) { if (Context.getCommandContext() != null) { if (cachedValue != null && cachedValue instanceof SerializableValue) { SerializableValue serializableValue = (SerializableValue) cachedValue; if(deserializeValue && !serializableValue.isDeserialized()) { cachedValue = null; } } <START> if (cachedValue != null && ((asTransientValue && !cachedValue.isTransient()) || !asTransientValue && cachedValue.isTransient())) { <END> cachedValue = null; } } if (cachedValue == null && errorMessage == null) { try { cachedValue = getSerializer().readValue(valueFields, deserializeValue, asTransientValue); if (notifyOnImplicitUpdates && isMutableValue(cachedValue)) { Context.getCommandContext().registerCommandContextListener(this); } } catch (RuntimeException e) { this.errorMessage = e.getMessage(); throw e; } } return cachedValue; }</code><technical_language>XOR here? If same, false, true clear cache. suggestion if (cachedValue != null && (asTransientValue ^ cachedValue.isTransient()) {</technical_language>

Target:
public TypedValue getTypedValue(boolean deserializeValue, boolean asTransientValue) { if (Context.getCommandContext() != null) { if (cachedValue != null && cachedValue instanceof SerializableValue) { SerializableValue serializableValue = (SerializableValue) cachedValue; if(deserializeValue && !serializableValue.isDeserialized()) { cachedValue = null; } } if (cachedValue != null && (asTransientValue ^ cachedValue.isTransient())) { cachedValue = null; } } if (cachedValue == null && errorMessage == null) { try { cachedValue = getSerializer().readValue(valueFields, deserializeValue, asTransientValue); if (notifyOnImplicitUpdates && isMutableValue(cachedValue)) { Context.getCommandContext().registerCommandContextListener(this); } } catch (RuntimeException e) { this.errorMessage = e.getMessage(); throw e; } } return cachedValue; }
Source:
<code>public void updateIndex( String resource, GeoEntryExtractor geoEntryExtractor, boolean create, ProgressCallback progressCallback) throws GeoEntryExtractionException, GeoNamesRemoteDownloadException { if (StringUtils.isBlank(resource)) { LOGGER.debug("The resource was null or empty."); return; } if (resourceProcessed(resource)) { LOGGER.trace("{} has already been processed", resource); return; } final List<GeoEntry> geoEntries = new ArrayList<>(); final GeoEntryExtractor.ExtractionCallback extractionCallback = new GeoEntryExtractor.ExtractionCallback() { @Override public void extracted(final GeoEntry newEntry) { geoEntries.add(newEntry); } @Override public void updateProgress(final int progress) { if (progressCallback != null) { progressCallback.updateProgress(progress); } } }; geoEntryExtractor.pushGeoEntriesToExtractionCallback(resource, extractionCallback); if (CollectionUtils.isEmpty(geoEntries)) { LOGGER.debug("No metacards were created from the resource."); return; } <START> updateIndex(geoEntries, create, progressCallback, resource); <END> LOGGER.trace("All data created for: {}", resource); fileProcessingComplete(resource); }</code><technical_language>So, automatically update index get added GeoNames Catalog Indexer. if added other ways? if CSW for example inject a gazetteer record</technical_language>

Target:
public void updateIndex( String resource, GeoEntryExtractor geoEntryExtractor, boolean create, ProgressCallback progressCallback) throws GeoEntryIndexingException, GeoEntryExtractionException, GeoNamesRemoteDownloadException { if (StringUtils.isBlank(resource)) { LOGGER.debug("The resource was null or empty."); return; } if (resourceProcessed(resource)) { LOGGER.trace("{} has already been processed", resource); return; } List<Metacard> metacardList = new ArrayList<>(); final GeoEntryExtractor.ExtractionCallback extractionCallback = new GeoEntryExtractor.ExtractionCallback() { @Override public void extracted(final GeoEntry newEntry) throws GeoEntryIndexingException { Metacard metacard = transformGeoEntryToMetacard(newEntry); if (metacard != null) { metacardList.add(metacard); } } @Override public void updateProgress(final int progress) { if (progressCallback != null) { progressCallback.updateProgress(progress); } } }; if (create) { RetryPolicy retryPolicy = new RetryPolicy() .withDelay(10, TimeUnit.SECONDS) .withMaxDuration(5, TimeUnit.MINUTES) .retryOn(Exception.class); Failsafe.with(retryPolicy) .run(() -> removeGeoNamesMetacardsFromCatalog(resource, extractionCallback)); } geoEntryExtractor.pushGeoEntriesToExtractionCallback(resource, extractionCallback); if (CollectionUtils.isEmpty(metacardList)) { LOGGER.debug("No Metacards were created from the resource."); return; } executeCreateMetacardRequest(metacardList); LOGGER.trace("All data created for: {}", resource); fileProcessingComplete(resource); }
Source:
<code>private static void resolveActiveNic(VDS vds){ InetAddress mgmt = null; try { mgmt = InetAddress.getByName(vds.getHostName()); <START> } catch (SecurityException ex) { <END> log.warn("Fail to resolve host ip by name '{}', Details: '{}' ", vds.getHostName(), ex.toString()); log.debug("Exception", ex); return; } catch (UnknownHostException ex) { log.warn("Fail to resolve host ip by name '{}', Details: '{}' ", vds.getHostName(), ex.toString()); log.debug("Exception", ex); return; } String mgmtAdd = mgmt.getHostAddress().trim(); for (VdsNetworkInterface iface : vds.getInterfaces()) { if (iface.getAddress().equals(mgmtAdd)){ vds.setActiveNic(iface.getName()); } } }</code><technical_language>difference in handle exceptions, group a single catch (Exception ex) statement</technical_language>

Target:
private static String resolveActiveNic(VDS vds){ InetAddress mgmt = null; try { mgmt = InetAddress.getByName(vds.getHostName()); } catch (Exception ex) { log.warn("Fail to resolve host ip by name '{}', Details: '{}' ", vds.getHostName(), ex.toString()); log.debug("Exception", ex); return null; } final String mgmtAdd = mgmt.getHostAddress().trim(); for (VdsNetworkInterface iface : vds.getInterfaces()) { if (iface.getAddress().equals(mgmtAdd)){ vds.setActiveNic(iface.getName()); return mgmtAdd; } } return mgmtAdd; }
Source:
<code><START> public Object getChromedriverArgs() { <END> return getCapability(AndroidMobileCapabilityType.CHROMEDRIVER_ARGS); }</code><technical_language>Object</technical_language>

Target:
public List<String> getChromedriverArgs() { return (List<String>) getCapability(AndroidMobileCapabilityType.CHROMEDRIVER_ARGS); }
Source:
<code>public int hashCode() { <START> int result = super.hashCode(); <END> result = ~~result; result = 31 * result + (defaultValue != null ? defaultValue.hashCode() : 0); result = ~~result; return result; }</code><technical_language>I exists org.kie.workbench.common.stunner.core.util.HashUtil class, if this logic, move class in some public static mehtod</technical_language>

Target:
public int hashCode() { return HashUtil.combineHashCodes(Objects.hashCode(defaultValue)); }
Source:
<code>public void testLoopback() { final InterfaceParams ifParams = InterfaceParams.getByName("lo"); <START> assertTrue(ifParams <END> != null); assertEquals("lo", ifParams.name); assertTrue(ifParams.index > 0); assertTrue(ifParams.macAddr != null); assertTrue(ifParams.defaultMtu >= NetworkConstants.ETHER_MTU); }</code><technical_language>assertNotNull</technical_language>

Target:
public void testLoopback() { final InterfaceParams ifParams = InterfaceParams.getByName("lo"); assertNotNull(ifParams); assertEquals("lo", ifParams.name); assertTrue(ifParams.index > 0); assertNotNull(ifParams.macAddr); assertTrue(ifParams.defaultMtu >= NetworkConstants.ETHER_MTU); }
Source:
<code>public void insertRollups(List<SingleRollupWriteContext> writeContexts) { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { Timer.Context writeOnlyTimer = startWriteTimer(); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = getIO(rollupType.name().toLowerCase(), granularity); ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } } finally { writeOnlyTimer.stop(); } try { for (final ResultSetFuture future : futureLocatorMap.keySet()) { final SingleRollupWriteContext writeContext = futureLocatorMap.get(future); Timer.Context resultsWaitTimer = startWaitResultsTimer(); try { future.getUninterruptibly().all(); } catch (Exception ex) { Instrumentation.markWriteError(); LOG.error(String.format("error writing locator %s, granularity %s, timestamp %d", writeContext.getLocator(), writeContext.getGranularity(), writeContext.getTimestamp()), ex); } finally { resultsWaitTimer.stop(); } } } finally { <START> <END> } } finally { ctx.stop(); } }</code><technical_language>is this try/finally block necessary</technical_language>

Target:
public void insertRollups(List<SingleRollupWriteContext> writeContexts) { if (writeContexts.size() == 0) { return; } Map<ResultSetFuture, SingleRollupWriteContext> futureLocatorMap = new HashMap<ResultSetFuture, SingleRollupWriteContext>(); Timer.Context ctx = Instrumentation.getWriteTimerContext( writeContexts.get( 0 ).getDestinationCF().getName() ); try { for (SingleRollupWriteContext writeContext : writeContexts) { Rollup rollup = writeContext.getRollup(); Locator locator = writeContext.getLocator(); Granularity granularity = writeContext.getGranularity(); int ttl = getTtl(locator, rollup.getRollupType(), granularity); RollupType rollupType = writeContext.getRollup().getRollupType(); DAbstractMetricIO io = getIO(rollupType.name().toLowerCase(), granularity); ResultSetFuture future = io.putAsync(locator, writeContext.getTimestamp(), rollup, writeContext.getGranularity(), ttl); futureLocatorMap.put(future, writeContext); } for (final ResultSetFuture future : futureLocatorMap.keySet()) { try { future.getUninterruptibly().all(); } catch (Exception ex) { Instrumentation.markWriteError(); final SingleRollupWriteContext writeContext = futureLocatorMap.get(future); LOG.error(String.format("error writing locator %s, granularity %s, timestamp %d", writeContext.getLocator(), writeContext.getGranularity(), writeContext.getTimestamp()), ex); } } } finally { ctx.stop(); } }
Source:
<code>private synchronized void drawHistory() { if (null == coordinates) { return; } historyObjs.removeAll(); final ArrayList<Location> paintHistory = getHistory(); paintHistory.add(coordinates); final int size = paintHistory.size(); if (size == 1) { return; } Location prev = paintHistory.get(0); int current = 1; while (current < size) { final List<LatLng> points = new ArrayList<>(MAX_HISTORY_POINTS); points.add(new LatLng(prev.getLatitude(), prev.getLongitude())); boolean paint = false; while (!paint && current < size) { final Location now = paintHistory.get(current); current++; if (now.distanceTo(prev) < LINE_MAXIMUM_DISTANCE_METERS) { points.add(new LatLng(now.getLatitude(), now.getLongitude())); } else { paint = true; } prev = now; } if (points.size() > 1) { historyObjs.addPolyline(new PolylineOptions() .addAll(points) .color(0xFFFFFFFF) <START> .width(DisplayUtils.getThinLineWidth() / 2f) <END> .zIndex(ZINDEX_HISTORY) ); historyObjs.addPolyline(new PolylineOptions() .addAll(points) .color(trailColor) .width(DisplayUtils.getThinLineWidth()) .zIndex(ZINDEX_HISTORY_SHADOW) ); } } }</code><technical_language>this a separate method a separate constant</technical_language>

Target:
private synchronized void drawHistory() { if (null == coordinates) { return; } historyObjs.removeAll(); final ArrayList<Location> paintHistory = getHistory(); paintHistory.add(coordinates); final int size = paintHistory.size(); if (size == 1) { return; } Location prev = paintHistory.get(0); int current = 1; while (current < size) { final List<LatLng> points = new ArrayList<>(MAX_HISTORY_POINTS); points.add(new LatLng(prev.getLatitude(), prev.getLongitude())); boolean paint = false; while (!paint && current < size) { final Location now = paintHistory.get(current); current++; if (now.distanceTo(prev) < LINE_MAXIMUM_DISTANCE_METERS) { points.add(new LatLng(now.getLatitude(), now.getLongitude())); } else { paint = true; } prev = now; } if (points.size() > 1) { historyObjs.addPolyline(new PolylineOptions() .addAll(points) .color(0xFFFFFFFF) .width(DisplayUtils.getThinLineInsetWidth()) .zIndex(ZINDEX_HISTORY) ); historyObjs.addPolyline(new PolylineOptions() .addAll(points) .color(trailColor) .width(DisplayUtils.getThinLineWidth()) .zIndex(ZINDEX_HISTORY_SHADOW) ); } } }
Source:
<code>public void init() { try { MockVaadinServlet servlet = (MockVaadinServlet) getServlet(); servlet.service = this; ServletConfig config = Mockito.mock(ServletConfig.class); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(config.getServletContext()).thenReturn(context); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(resourceProvider); Mockito.when(context.getAttribute(Lookup.class.getName())) .thenReturn(lookup); <START> if ( getServlet().getServletConfig() ==null) { <END> getServlet().init(config); } super.init(); } catch (ServiceException | ServletException e) { throw new RuntimeException(e); } }</code><technical_language>This instead a check beginning of init if if(this.equals(getServlet())) return; mocks included if in this case Basically wrong creation constructor init create instantiator set again. a constructor takes in instantiator init is called tests</technical_language>

Target:
public void init() { try { MockVaadinServlet servlet = (MockVaadinServlet) getServlet(); servlet.service = this; if (getServlet().getServletConfig() == null) { ServletConfig config = Mockito.mock(ServletConfig.class); ServletContext context = Mockito.mock(ServletContext.class); Mockito.when(config.getServletContext()).thenReturn(context); Mockito.when(lookup.lookup(ResourceProvider.class)) .thenReturn(resourceProvider); Mockito.when(context.getAttribute(Lookup.class.getName())) .thenReturn(lookup); getServlet().init(config); } super.init(); } catch (ServiceException | ServletException e) { throw new RuntimeException(e); } }
Source:
<code>protected boolean setAndValidateDiskProfiles() { if (getParameters().getVmTemplate().getDiskList() != null) { Map<DiskImage, Guid> map = new HashMap<>(); <START> for (Disk disk : getParameters().getVmTemplate().getDiskList()) { <END> if (disk instanceof DiskImage) { DiskImage diskImage = (DiskImage) disk; map.put(diskImage, imageToDestinationDomainMap.get(diskImage.getId())); } } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }</code><technical_language>/s/Disk/DiskImage</technical_language>

Target:
protected boolean setAndValidateDiskProfiles() { if (getParameters().getVmTemplate().getDiskList() != null) { Map<DiskImage, Guid> map = new HashMap<>(); for (DiskImage diskImage : getParameters().getVmTemplate().getDiskList()) { if (diskImage.getDiskStorageType() == DiskStorageType.IMAGE) { map.put(diskImage, imageToDestinationDomainMap.get(diskImage.getId())); } } return validate(DiskProfileHelper.setAndValidateDiskProfiles(map)); } return true; }
Source:
<code>@Override public <T> IgniteInternalFuture<EntryProcessorResult<T>> invokeAsync( final K key, final EntryProcessor<K, V, T> entryProcessor, final Object... args) throws EntryProcessorException { A.notNull(key, "key", entryProcessor, "entryProcessor"); if (keyCheck) validateCacheKey(key); IgniteInternalFuture<?> fut = asyncOp(new AsyncOp() { @Override public IgniteInternalFuture op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) { Map<? extends K, EntryProcessor<K, V, Object>> invokeMap = Collections.singletonMap(key, (EntryProcessor<K, V, Object>)entryProcessor); return tx.invokeAsync(ctx, readyTopVer, invokeMap, args); } @Override public String toString() { return S.toString("invokeAsync", "key", key, true, "entryProcessor", entryProcessor, false); } }); IgniteInternalFuture<GridCacheReturn> fut0 = (IgniteInternalFuture<GridCacheReturn>)fut; return fut0.chain(new CX1<IgniteInternalFuture<GridCacheReturn>, EntryProcessorResult<T>>() { @Override public EntryProcessorResult<T> applyx(IgniteInternalFuture<GridCacheReturn> fut) throws IgniteCheckedException { GridCacheReturn ret = fut.get(); Map<K, EntryProcessorResult<T>> resMap = ret.value(); if (resMap != null) { assert resMap.isEmpty() || resMap.size() == 1 : resMap.size(); <START> return resMap.isEmpty() ? new CacheInvokeResult<T>() : resMap.values().iterator().next(); <END> } return new CacheInvokeResult<>(); } }); }</code><technical_language>I remove generic type</technical_language>

Target:
@Override public <T> IgniteInternalFuture<EntryProcessorResult<T>> invokeAsync( final K key, final EntryProcessor<K, V, T> entryProcessor, final Object... args) throws EntryProcessorException { A.notNull(key, "key", entryProcessor, "entryProcessor"); if (keyCheck) validateCacheKey(key); IgniteInternalFuture<?> fut = asyncOp(new AsyncOp() { @Override public IgniteInternalFuture op(GridNearTxLocal tx, AffinityTopologyVersion readyTopVer) { Map<? extends K, EntryProcessor<K, V, Object>> invokeMap = Collections.singletonMap(key, (EntryProcessor<K, V, Object>)entryProcessor); return tx.invokeAsync(ctx, readyTopVer, invokeMap, args); } @Override public String toString() { return S.toString("invokeAsync", "key", key, true, "entryProcessor", entryProcessor, false); } }); IgniteInternalFuture<GridCacheReturn> fut0 = (IgniteInternalFuture<GridCacheReturn>)fut; return fut0.chain(new CX1<IgniteInternalFuture<GridCacheReturn>, EntryProcessorResult<T>>() { @Override public EntryProcessorResult<T> applyx(IgniteInternalFuture<GridCacheReturn> fut) throws IgniteCheckedException { GridCacheReturn ret = fut.get(); Map<K, EntryProcessorResult<T>> resMap = ret.value(); if (resMap != null) { assert resMap.isEmpty() || resMap.size() == 1 : resMap.size(); return resMap.isEmpty() ? new CacheInvokeResult<>() : resMap.values().iterator().next(); } return new CacheInvokeResult<>(); } }); }
Source:
<code>private static ThirdPartyContext newContext(String name, boolean multitenant) { BoundedContext context = notStoringEvents(name, multitenant).build(); context.integrationBus() <START> .notifyOfCurrentNeeds(); <END> return new ThirdPartyContext(context); }</code><technical_language>need name this method tells fact Contexts need speak other, again, a new context appeared in picture of system</technical_language>

Target:
private static ThirdPartyContext newContext(String name, boolean multitenant) { checkNotEmptyOrBlank(name); BoundedContext context = notStoringEvents(name, multitenant).build(); context.integrationBus() .notifyOthers(); return new ThirdPartyContext(context); }
Source:
<code>public String toString() { <START> return String.format("%s, diskId = %s", super.toString(), disk.getId()); <END> }</code><technical_language>forgot add address toString() in patch master branch</technical_language>

Target:
public String toString() { return String.format("%s, diskId = %s, addressMap = %s", super.toString(), disk.getId(), getAddressMap()); }
Source:
<code>protected Product validateProductReferences(Product entity) { for (Map.Entry<String, String> entry : entity.getAttributes().entrySet()) { this.attributeValidator.validate(entry.getKey(), entry.getValue()); } if (entity.getProductContent() != null) { for (ProductContent pc : entity.getProductContent()) { if (pc.getContent() == null) { throw new IllegalStateException( "Product contains a ProductContent with a null content reference"); } pc.setProduct(entity); } } <START> if (entity.getBranding() != null) { <END> for (Branding brand : entity.getBranding()) { if (brand.getProductId() == null || brand.getName() == null || brand.getType() == null) { throw new IllegalStateException( "Product contains a Branding with a null product id, name or type."); } } } return entity; }</code><technical_language>I if a point isComplete method entities check this kind of needing this kind of code in a number of places</technical_language>

Target:
protected Product validateProductReferences(Product entity) { for (Map.Entry<String, String> entry : entity.getAttributes().entrySet()) { this.attributeValidator.validate(entry.getKey(), entry.getValue()); } if (entity.getProductContent() != null) { for (ProductContent pc : entity.getProductContent()) { if (pc.getContent() == null) { throw new IllegalStateException( "Product contains a ProductContent with a null content reference"); } pc.setProduct(entity); } } if (entity.getBranding() != null) { for (ProductBranding brand : entity.getBranding()) { if (brand.getProductId() == null || brand.getName() == null || brand.getType() == null) { throw new IllegalStateException( "Product contains a Branding with a null product id, name or type."); } brand.setProduct(entity); } } return entity; }
Source:
<code>public void verifyPseudoConflictDetection() throws IOException { <START> final IComparisonScope scope = new DefaultComparisonScope(rightAndLeftModel, rightAndLeftModel, <END> origin); final Comparison comparison = EMFCompare.builder().build().compare(scope); EList<Conflict> conflicts = comparison.getConflicts(); assertEquals(numberOfConflicts, conflicts.size()); for (Conflict conflict : conflicts) { assertEquals(ConflictKind.PSEUDO, conflict.getKind()); } }</code><technical_language>instance for left right</technical_language>

Target:
public void verifyPseudoConflictDetection() throws IOException { final IComparisonScope scope = new DefaultComparisonScope(left, right, origin); final Comparison comparison = EMFCompare.builder().build().compare(scope); EList<Conflict> conflicts = comparison.getConflicts(); assertEquals(numberOfConflicts, conflicts.size()); for (Conflict conflict : conflicts) { assertEquals(ConflictKind.PSEUDO, conflict.getKind()); } }
Source:
<code>public String toString () { StringBuilder result = new StringBuilder(); for (int i = 0; i < data.length; i += 3) { <START> result.append(Float.toString(data[i])).append(", ").append(Float.toString(data[i + 1])).append(", ").append(Float.toString(data[i + 2])).append("\n"); <END> } return result.toString(); }</code><technical_language>StringBuilder.append(data[i]) Float.toString() more efficient</technical_language>

Target:
public String toString () { StringBuilder result = new StringBuilder(); for (int i = 0; i < data.length; i += 3) { result.append(data[i]).append(", ").append(data[i + 1]).append(", ").append(data[i + 2]).append("\n"); } return result.toString(); }
Source:
<code>public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } TypeArgumentConstraintLocation that = (TypeArgumentConstraintLocation) o; if ( !typeParameter.equals( that.typeParameter ) ) { return false; } if ( delegate != null ? !delegate.equals( that.delegate ) : that.delegate != null ) { return false; <START> } <END> if ( !typeForValidatorResolution.equals( that.typeForValidatorResolution ) ) { return false; } return true; }</code><technical_language>I null</technical_language>

Target:
public boolean equals(Object o) { if ( this == o ) { return true; } if ( o == null || getClass() != o.getClass() ) { return false; } TypeArgumentConstraintLocation that = (TypeArgumentConstraintLocation) o; if ( !typeParameter.equals( that.typeParameter ) ) { return false; } if ( !delegate.equals( that.delegate ) ) { return false; } return true; }
Source:
<code>private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Set<String> lunsList = new <START> HashSet<>(lunIds); <END> for (LUNs lun : lunsFromDb) { if (lunsList.contains(lun.getLUN_id())) { lunsList.remove(lun.getLUN_id()); } } return lunsList.isEmpty(); }</code><technical_language>kind of confusing a set named "List", consider change that</technical_language>

Target:
private boolean checkLunsInStorageDomain(List<String> lunIds, StorageDomain storageDomain) { List<LUNs> lunsFromDb = getLunDao().getAllForVolumeGroup(getStorageDomain().getStorage()); Set<String> lunsSet = new HashSet<>(lunIds); for (LUNs lun : lunsFromDb) { if (lunsSet.contains(lun.getLUN_id())) { lunsSet.remove(lun.getLUN_id()); } } return lunsSet.isEmpty(); }
Source:
<code>public long getAvgExecutionTime() { long avgExecTime = -1; try { synchronized (this) { avgExecTime = totalExecutionTime / invocationCnt; <START> } <END> } catch (Exception e) { if (invocationCnt == 0 && totalExecutionTime == 0) { avgExecTime = 0; } } return avgExecTime; }</code><technical_language>is synchronized block 'try' part of try-catch block? 'catch' part run in synchronized block</technical_language>

Target:
public long getAvgExecutionTime() { long avgExecTime = -1; synchronized (this) { try { avgExecTime = totalExecutionTime / invocationCnt; } catch (Exception e) { if (invocationCnt == 0 && totalExecutionTime == 0) { avgExecTime = 0; } } } return avgExecTime; }
Source:
<code>public void visitCallExpression(PyCallExpressionTree pyCallExpressionTree) { super.visitCallExpression(pyCallExpressionTree); Symbol symbol = symbolTable.getSymbol(pyCallExpressionTree.callee()); if(symbol != null) { <START> System.out.println(symbol.qualifiedName()); <END> funcNames.add(symbol.qualifiedName()); } }</code><technical_language>I forgot remove this line</technical_language>

Target:
public void visitCallExpression(PyCallExpressionTree pyCallExpressionTree) { super.visitCallExpression(pyCallExpressionTree); Symbol symbol = symbolTable.getSymbol(pyCallExpressionTree.callee()); if(symbol != null) { funcNames.add(symbol.qualifiedName()); } }
Source:
<code>public boolean deleteBlog(Context ctx, int id) { int rowsAffected = db.delete(BLOGS_TABLE, "id=?", new String[]{Integer.toString(id)}); deleteQuickPressShortcutsForLocalTableBlogId(ctx, id); deleteAllPostsForLocalTableBlogId(id); <START> PeopleTable.deletePeopleForBlog(id); <END> return (rowsAffected > 0); }</code><technical_language>I a good idea rename this deletePeopleForLocalBlogId clear a **local** blog ID</technical_language>

Target:
public boolean deleteBlog(Context ctx, int id) { int rowsAffected = db.delete(BLOGS_TABLE, "id=?", new String[]{Integer.toString(id)}); deleteQuickPressShortcutsForLocalTableBlogId(ctx, id); deleteAllPostsForLocalTableBlogId(id); PeopleTable.deletePeopleForLocalBlogId(id); return (rowsAffected > 0); }
Source:
<code>public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(HDInsight36Constant.SPARK_MODULE_GROUP.getModuleName(), false, condition)); <START> hs.add(new DistributionModuleGroup(HDInsight36Constant.BIGDATALAUNCHER_MODULE_GROUP.getModuleName())); <END> hs.add(new DistributionModuleGroup(HDInsight36Constant.HDINSIGHT36COMMON_MODULE_GROUP.getModuleName(), false, condition)); return hs; }</code><technical_language>2 arguments control jar is MRRequired if meets "not local spark" condition. requirements jar loaded</technical_language>

Target:
public static Set<DistributionModuleGroup> getModuleGroups() { Set<DistributionModuleGroup> hs = new HashSet<>(); hs.add(new DistributionModuleGroup(HDInsight36Constant.SPARK_MODULE_GROUP.getModuleName(), false, condition)); hs.add(new DistributionModuleGroup(HDInsight36Constant.BIGDATALAUNCHER_MODULE_GROUP.getModuleName(), false, condition)); hs.add(new DistributionModuleGroup(HDInsight36Constant.HDINSIGHT36COMMON_MODULE_GROUP.getModuleName(), false, condition)); return hs; }
Source:
<code>public SnmpAgentConfig getAgentConfig(final InetAddress address, String location) { <START> final SnmpAgentConfigProxyMapper mapper = SnmpAgentConfigProxyMapper.getInstance(); <END> final SnmpAgentAddress agentAddress = mapper.getAddress(address); final String addressString = str(address); if (agentAddress == null) { LOG.debug( "No agent address mapping found for {}! Try adding a @JUnitSnmpAgent(host=\"{}\", resource=\"...\" entry...", addressString, addressString); return super.getAgentConfig(address); } final SnmpAgentConfig config = new SnmpAgentConfig(agentAddress.getAddress()); config.setProxyFor(address); config.setPort(agentAddress.getPort()); LOG.debug("proxying -> {}", addressString, agentAddress); return config; }</code><technical_language>Is reason SnmpAgentConfigProxyMapper needs this singleton pattern</technical_language>

Target:
public SnmpAgentConfig getAgentConfig(final InetAddress address, String location) { final SnmpAgentConfigProxyMapper mapper = SnmpAgentConfigProxyMapper.getInstance(); final SnmpAgentAddress agentAddress = mapper.getAddress(address); final String addressString = str(address); if (agentAddress == null) { LOG.debug( "No agent address mapping found for {}! Try adding a @JUnitSnmpAgent(host=\"{}\", resource=\"...\" entry...", addressString, addressString); return super.getAgentConfig(address, location); } final SnmpAgentConfig config = new SnmpAgentConfig(agentAddress.getAddress()); config.setProxyFor(address); config.setPort(agentAddress.getPort()); LOG.debug("proxying -> {}", addressString, agentAddress); return config; }
Source:
<code>public int getAvailableWidth(int requestedOffset) { <START> int totalWidth = fTimeAlignedComposite.getSize().x; <END> int availableWidth = totalWidth - requestedOffset; return availableWidth; }</code><technical_language>inline this maybe</technical_language>

Target:
public int getAvailableWidth(int requestedOffset) { return fTimeAlignedComposite.getSize().x - requestedOffset; }
Source:
<code>void putTicket() { <START> imageioClient.putTicket(imageTicket); <END> }</code><technical_language>assert this throw. Need check ticket exists in daemon getTicket()</technical_language>

Target:
void putTicket() { assertDoesNotThrow(() -> imageioClient.putTicket(imageTicket)); }
Source:
<code>public void testBrownAndBlack() { String[] input = { "brown", "black" }; int expected = 10; <START> int received = resistorColorDuo.colorCode(input); <END> assertEquals(expected, received); }</code><technical_language>Instead of received, I prefer actual</technical_language>

Target:
public void testBrownAndBlack() { String[] input = { "brown", "black" }; int expected = 10; int actual = resistorColorDuo.value(input); assertEquals(expected, actual); }
Source:
<code>public void processBarrier(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); if (currentCheckpointId > barrierId || (currentCheckpointId == barrierId && !isCheckpointPending())) { return; } if (currentCheckpointId < barrierId) { if (isCheckpointPending()) { cancelSubsumedCheckpoint(barrierId); } markCheckpointStart(barrier.getTimestamp()); currentCheckpointId = barrierId; numBarriersReceived = 0; allBarriersReceivedFuture = new CompletableFuture<>(); checkpointCoordinator.initCheckpoint(barrierId, barrier.getCheckpointOptions()); for (final InputGate gate : inputGates) { for (int index = 0, numChannels = gate.getNumberOfInputChannels(); index < numChannels; index++) { gate.getChannel(index).checkpointStarted(barrier); } } notifyCheckpoint(barrier, 0); } if (currentCheckpointId == barrierId) { LOG.debug("{}: Received barrier from channel @ {}.", taskName, channelInfo, barrierId); if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); <START> for (final InputGate gate : inputGates) { for (int index = 0, numChannels = gate.getNumberOfInputChannels(); index < numChannels; index++) { gate.getChannel(index).checkpointStopped(currentCheckpointId); } } <END> } } }</code><technical_language>story this change? 1. differs a single line numBarriersReceived = 0;, deduplicate some code 2. explain functional change? 3. missing a unit test for that? answer point 2., if a bug discovered in e2e test, nice a faster unit test for well</technical_language>

Target:
public void processBarrier(CheckpointBarrier barrier, InputChannelInfo channelInfo) throws IOException { long barrierId = barrier.getId(); if (currentCheckpointId > barrierId || (currentCheckpointId == barrierId && !isCheckpointPending())) { return; } if (currentCheckpointId < barrierId) { if (isCheckpointPending()) { cancelSubsumedCheckpoint(barrierId); } markCheckpointStart(barrier.getTimestamp()); currentCheckpointId = barrierId; numBarriersReceived = 0; allBarriersReceivedFuture = new CompletableFuture<>(); checkpointCoordinator.initCheckpoint(barrierId, barrier.getCheckpointOptions()); for (final InputGate gate : inputGates) { for (int index = 0, numChannels = gate.getNumberOfInputChannels(); index < numChannels; index++) { gate.getChannel(index).checkpointStarted(barrier); } } notifyCheckpoint(barrier, 0); } if (currentCheckpointId == barrierId) { LOG.debug("{}: Received barrier from channel @ {}.", taskName, channelInfo, barrierId); if (++numBarriersReceived == numOpenChannels) { allBarriersReceivedFuture.complete(null); resetPendingCheckpoint(barrierId); } } }
Source:
<code>private void onEnd(WorkflowExecutionContext context){ if (Boolean.parseBoolean(ENABLE_POSTPROCESSING)) { return; } while(0<blockingQueue.remainingCapacity()){ try { LOG.debug("Sleeping, no capacity in threadpool...."); TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { <START> e.printStackTrace(); <END> } } executorService.execute(new LogMover(context)); }</code><technical_language>missed this review. Please logger log exception</technical_language>

Target:
private void onEnd(WorkflowExecutionContext context){ if (Boolean.parseBoolean(ENABLE_POSTPROCESSING)) { return; } while(0<blockingQueue.remainingCapacity()){ try { LOG.trace("Sleeping, no capacity in threadpool...."); TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { LOG.error("Exception in LogMoverService", e); } } executorService.execute(new LogMover(context)); }
Source:
<code>public static <T> void shuffleHead(@NonNull T[] elements, int n) { <START> shuffleHead(elements, n, ThreadLocalRandom.current()::nextInt); <END> }</code><technical_language>a small overhead translate method reference call. if significant not, avoid altogether passing ThreadLocalRandom instead of method. mock in test: java ThreadLocalRandom random = Mockito.mock(ThreadLocalRandom.class); Mockito.when(random.nextInt(Mockito.anyInt())).thenAnswer((invocation) -> { int i = invocation.getArgument(0); return i - 2; });</technical_language>

Target:
public static <T> void shuffleHead(@NonNull T[] elements, int n) { shuffleHead(elements, n, ThreadLocalRandom.current()); }