auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void allThreadMustHaveTheirOwnThreadLocalSimpleDateFormat() { int numberOfParties = 10; final CyclicBarrier barrier = new CyclicBarrier(numberOfParties + 1); final List<SimpleDateFormat> list = Collections.synchronizedList(new ArrayList<SimpleDateFormat>()); <START> class Worker implements Runnable { <END> @Override public void run() { try { list.add(SafeCalendarJsonAdapter.DATE_FORMAT_MAP.get(SafeCalendarJsonAdapter.REG_EX_YEAR).get()); barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } } } for (int index = 0; index < numberOfParties; ++index) { new Thread(new Worker()).start(); } try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } for (int i = 0; i < numberOfParties; ++i) { for (int j = 0; j < numberOfParties; ++j) { if (i == j) { continue; } SimpleDateFormat simpleDateFormatToCheck = list.get(i); SimpleDateFormat simpleDateFormatToVerify = list.get(j); if (simpleDateFormatToCheck == simpleDateFormatToVerify) { fail("Each thread should have it own instanse of thread SimpleDateFormat local variable"); return; } } } }</code><technical_language>Uh, knew declare a class in a method - learn a new day! :)</technical_language>

Target:
public void allThreadMustHaveTheirOwnThreadLocalSimpleDateFormat() { int numberOfParties = 10; final CyclicBarrier barrier = new CyclicBarrier(numberOfParties + 1); final List<SimpleDateFormat> list = Collections.synchronizedList(new ArrayList<SimpleDateFormat>()); class Worker implements Runnable { @Override public void run() { try { list.add(SafeCalendarJsonAdapter.DATE_FORMAT_MAP.get(SafeCalendarJsonAdapter.REG_EX_YEAR).get()); barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } } } for (int index = 0; index < numberOfParties; ++index) { new Thread(new Worker()).start(); } try { barrier.await(); } catch (InterruptedException | BrokenBarrierException ex) { fail("InterruptedException or BrokenBarrierException thrown"); } for (int i = 0; i < numberOfParties; ++i) { for (int j = i; j < numberOfParties; ++j) { if (i == j) { continue; } SimpleDateFormat simpleDateFormatToCheck = list.get(i); SimpleDateFormat simpleDateFormatToVerify = list.get(j); if (simpleDateFormatToCheck == simpleDateFormatToVerify) { fail("Each thread should have it own instanse of thread SimpleDateFormat local variable"); return; } } } }
Source:
<code>private JsonObject getNamedPlaceholderValues(ParameterAccessor accessor) { JsonObject namedValues = JsonObject.create(); HashSet<String> pNames=new HashSet<>(parameterNames); for (Parameter parameter : this.queryMethod.getParameters().getBindableParameters()) { String placeholder = parameter.getPlaceholder(); Object value = couchbaseConverter.convertForWriteIfNeeded(accessor.getBindableValue(parameter.getIndex())); if (placeholder != null && placeholder.charAt(0) == ':') { placeholder = placeholder.replaceFirst(":", ""); <START> try { <END> namedValues.put(placeholder,value); }catch(InvalidArgumentException iae){ Object o = accessor.getBindableValue(parameter.getIndex()); if(o instanceof Object[]) { Object[] array=(Object[])o; JsonArray ja=JsonValue.ja(); for(Object e:array) { ja.add(String.valueOf(couchbaseConverter.convertForWriteIfNeeded(e))); } namedValues.put(placeholder,ja); } else { throw iae; } } if(pNames.contains(placeholder)) pNames.remove(placeholder); else throw new RuntimeException("parameter named "+placeholder+ " does not match any named parameter "+parameterNames+ " in "+statement); } else { if(parameter.getName().isPresent()) namedValues.put(parameter.getName().get(), value); else throw new RuntimeException("cannot determine argument for named parameter. "+ "Argument "+ parameter.getIndex() +" to "+ queryMethod.getClass().getName()+"."+queryMethod.getName()+ "() needs @Param(\"name\") that matches a named parameter in "+ statement); } } if(!pNames.isEmpty()) throw new RuntimeException("no parameter found for "+pNames); return namedValues; }</code><technical_language>Another instance of deep nesting proper formatting. Please extract some sort of utility methods</technical_language>

Target:
private JsonObject getNamedPlaceholderValues(ParameterAccessor accessor) { JsonObject namedValues = JsonObject.create(); HashSet<String> pNames = new HashSet<>(parameterNames); for (Parameter parameter : this.queryMethod.getParameters().getBindableParameters()) { String placeholder = parameter.getPlaceholder(); Object rawValue = accessor.getBindableValue(parameter.getIndex()); Object value = couchbaseConverter.convertForWriteIfNeeded(rawValue); if (placeholder != null && placeholder.charAt(0) == ':') { placeholder = placeholder.replaceFirst(":", ""); putNamedValue(accessor, parameter, namedValues, placeholder, value); if (pNames.contains(placeholder)) { pNames.remove(placeholder); } else { throw new RuntimeException( "parameter named " + placeholder + " does not match any named parameter " + parameterNames + " in " + statement); } } else { if (parameter.getName().isPresent()) { putNamedValue(accessor, parameter, namedValues, parameter.getName().get(), value); } else { throw new RuntimeException( "cannot determine argument for named parameter. " + "Argument " + parameter.getIndex() + " to " + queryMethod.getClass().getName() + "." + queryMethod.getName() + "() needs @Param(\"name\") that matches a named parameter in " + statement); } } } if (!pNames.isEmpty()) { throw new RuntimeException("no parameter found for " + pNames); } return namedValues; }
Source:
<code>public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); this.repositoryObservable.register(adapter); <START> this.listeners.add(adapter); <END> }</code><technical_language>lines be: if ( this.repositoryObservable.register(adapter) ) this.listeners.add(adapter); in case register adapter (for reason)</technical_language>

Target:
public void addEventListener( EventListener listener, int eventTypes, String absPath, boolean isDeep, String[] uuid, String[] nodeTypeName, boolean noLocal ) throws RepositoryException { CheckArg.isNotNull(listener, "listener"); checkSession(); JcrListenerAdapter adapter = new JcrListenerAdapter(listener, eventTypes, absPath, isDeep, uuid, nodeTypeName, noLocal); if (this.repositoryObservable.register(adapter)) { this.listeners.add(adapter); } }
Source:
<code>public void testInvokeByPassingNullValue() throws RemotingException { mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")); given(mockInvoker.invoke(any(Invocation.class))).willReturn(new RpcResult("ok")); mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20883")); DubboProtocol.getDubboProtocol().export(mockInvoker); try { invoke.telnet(mockChannel, "DemoService.add(null, 2)"); fail("It should cause a NullPointerException here."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.1 parameter is primitive(int), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.add(1, null)"); <START> fail("It should cause a NullPointerException here."); <END> } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.2 parameter is primitive(long), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.sayHello(null)"); } catch (NullPointerException ex) { fail("It shouldn't cause a NullPointerException here."); } }</code><technical_language>Is message right ? "It a NullPointerException here."</technical_language>

Target:
public void testInvokeByPassingNullValue() throws RemotingException { mockInvoker = mock(Invoker.class); given(mockInvoker.getInterface()).willReturn(DemoService.class); given(mockInvoker.getUrl()).willReturn(URL.valueOf("dubbo://127.0.0.1:20883/demo")); given(mockInvoker.invoke(any(Invocation.class))).willReturn(new RpcResult("ok")); mockChannel = mock(Channel.class); given(mockChannel.getAttribute("telnet.service")).willReturn("org.apache.dubbo.rpc.protocol.dubbo.support.DemoService"); given(mockChannel.getLocalAddress()).willReturn(NetUtils.toAddress("127.0.0.1:5555")); given(mockChannel.getRemoteAddress()).willReturn(NetUtils.toAddress("127.0.0.1:20883")); DubboProtocol.getDubboProtocol().export(mockInvoker); try { invoke.telnet(mockChannel, "DemoService.add(null, 2)"); fail("It should cause a NullPointerException by the above code."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.1 parameter is primitive(int), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.add(1, null)"); fail("It should cause a NullPointerException by the above code."); } catch (NullPointerException ex) { String message = ex.getMessage(); assertEquals("The type of No.2 parameter is primitive(long), but the value passed is null.", message); } try { invoke.telnet(mockChannel, "DemoService.sayHello(null)"); } catch (NullPointerException ex) { fail("It shouldn't cause a NullPointerException by the above code."); } }
Source:
<code>public static void setUp() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer bb = ByteBuffer.allocate(25); bb.order(ByteOrder.BIG_ENDIAN); bb.put((byte) 0x46); bb.put((byte) 0x9A); bb.put((byte) 0x00); bb.put((byte) 0xFF); bb.put((byte) 0x0F); bb.put((byte) 0xF0); bb.put((byte) 0x1E); bb.put((byte) 0xE1); bb.put((byte) 0xA0); bb.put((byte) 0xFE); bb.put((byte) 0x33); bb.put((byte) 0x44); bb.put((byte) 192); bb.put((byte) 168); bb.put((byte) 1); bb.put((byte) 0); bb.put((byte) 193); bb.put((byte) 169); bb.put((byte) 2); bb.put((byte) 1); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA6); bb.flip(); PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); <START> PcapFile dummy = trace.getTrace(); <END> IPv4Packet packet = new IPv4Packet(dummy, null, bb); ITmfEventField[] fieldArray = generatePacketFields(packet); fRegularField = new PcapEventField("Regular Field", EMPTY_STRING, fieldArray, packet); fRootField = new PcapRootEventField(fieldArray, packet); }</code><technical_language>try file close. try (PcapFile dummy = trace.getTrace())</technical_language>

Target:
public static void setUp() throws IOException, BadPcapFileException, BadPacketException { ByteBuffer bb = ByteBuffer.allocate(25); bb.order(ByteOrder.BIG_ENDIAN); bb.put((byte) 0x46); bb.put((byte) 0x9A); bb.put((byte) 0x00); bb.put((byte) 0xFF); bb.put((byte) 0x0F); bb.put((byte) 0xF0); bb.put((byte) 0x1E); bb.put((byte) 0xE1); bb.put((byte) 0xA0); bb.put((byte) 0xFE); bb.put((byte) 0x33); bb.put((byte) 0x44); bb.put((byte) 192); bb.put((byte) 168); bb.put((byte) 1); bb.put((byte) 0); bb.put((byte) 193); bb.put((byte) 169); bb.put((byte) 2); bb.put((byte) 1); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA2); bb.put((byte) 0x56); bb.put((byte) 0xA6); bb.flip(); PcapTestTrace trace = PcapTestTrace.MOSTLY_TCP; assumeTrue(trace.exists()); try (PcapFile dummy = trace.getTrace();) { IPv4Packet packet = new IPv4Packet(dummy, null, bb); ITmfEventField[] fieldArray = generatePacketFields(packet); fRegularField = new PcapEventField("Regular Field", EMPTY_STRING, fieldArray, packet); fRootField = new PcapRootEventField(fieldArray, packet); } }
Source:
<code>public int compareTo(DiskImageDynamic o) { <START> return BusinessEntityComparator.newGuidInstance().compare(this, o); <END> }</code><technical_language>newGuidInstance() method is redundant - use: BusinessEntityComparator.<DiskImageDynamic, Guid>newInstance().compare(this, o);</technical_language>

Target:
public int compareTo(DiskImageDynamic o) { return BusinessEntityComparator.<DiskImageDynamic, Guid>newInstance().compare(this, o); }
Source:
<code>public boolean filterOut(SAMRecord record) { <START> if (includeReads) { <END> if (values.contains(record.getAttribute(tag))) { return false; } } else { if (!values.contains(record.getAttribute(tag))) { return false; } } return true; }</code><technical_language>this work java return values.contains(record.getAttribute(tag))!=includeReads; ? simpler follow</technical_language>

Target:
public boolean filterOut(SAMRecord record) { return values.contains(record.getAttribute(tag)) != includeReads; }
Source:
<code><START> public void convertRelationshipToRelationshipField(final Relationship oldRelationship) throws DotDataException, DotSecurityException{ <END> final ContentType parentContentType = new StructureTransformer(oldRelationship.getParentStructure()).from(); final ContentType childContentType = new StructureTransformer(oldRelationship.getChildStructure()).from(); final com.dotcms.contenttype.model.field.Field parentRelationshipField = createRelationshipField(oldRelationship.getChildRelationName(),parentContentType.id(), oldRelationship.getCardinality(),oldRelationship.isChildRequired(),childContentType.variable()); createRelationshipField(oldRelationship.getParentRelationName(), childContentType.id(), oldRelationship.getCardinality(), oldRelationship.isParentRequired(), parentContentType.variable()+"."+parentRelationshipField.variable()); final Relationship newRelationship = byTypeValue(parentContentType.variable()+"."+parentRelationshipField.variable()); final DotConnect dc = new DotConnect (); dc.setSQL("update tree set relation_type = '" + newRelationship.getRelationTypeValue() + "' where relation_type = '" + oldRelationship.getRelationTypeValue() + "'"); dc.loadResult(); APILocator.getRelationshipAPI().delete(oldRelationship); APILocator.getContentletAPI().refresh(oldRelationship.getParentStructure()); APILocator.getContentletAPI().refresh(oldRelationship.getChildStructure()); }</code><technical_language>WrapInTransaction annotation</technical_language>

Target:
public void convertRelationshipToRelationshipField(final Relationship oldRelationship) throws DotDataException, DotSecurityException{ final ContentType parentContentType = new StructureTransformer(oldRelationship.getParentStructure()).from(); final ContentType childContentType = new StructureTransformer(oldRelationship.getChildStructure()).from(); final com.dotcms.contenttype.model.field.Field parentRelationshipField = createRelationshipField(oldRelationship.getChildRelationName(),parentContentType.id(), oldRelationship.getCardinality(),oldRelationship.isChildRequired(),childContentType.variable()); createRelationshipField(oldRelationship.getParentRelationName(), childContentType.id(), oldRelationship.getCardinality(), oldRelationship.isParentRequired(), parentContentType.variable()+"."+parentRelationshipField.variable()); final Relationship newRelationship = byTypeValue(parentContentType.variable()+"."+parentRelationshipField.variable()); final DotConnect dc = new DotConnect (); dc.setSQL("update tree set relation_type = ? where relation_type = ?"); dc.addParam(newRelationship.getRelationTypeValue()); dc.addParam(oldRelationship.getRelationTypeValue()); dc.loadResult(); APILocator.getRelationshipAPI().delete(oldRelationship); APILocator.getContentletAPI().refresh(oldRelationship.getParentStructure()); APILocator.getContentletAPI().refresh(oldRelationship.getChildStructure()); }
Source:
<code>void run() { <START> List<String> eventHubPartitionIds = new ArrayList<>(); <END> this.eventHubAsyncClient.getPartitionIds() .map(eventHubPartitionIds::add).blockLast(Duration.ofSeconds(1)); logger.info("Found partitions", eventHubPartitionIds.size()); List<PartitionOwnership> ownership = new ArrayList<>(); this.partitionManager .listOwnership(this.eventHubName, this.consumerGroupName) .map(ownership::add) .blockLast(Duration.ofSeconds(1)); logger.info("Got ownership info from partition manager"); List<PartitionOwnership> myOwnership = new ArrayList<>(); this.partitionManager .claimOwnership(ownership) .doOnNext(myOwnership::add) .blockLast(Duration.ofSeconds(1)); logger.info("Claimed ownership"); eventHubPartitionIds.forEach(this::receiveEvents); }</code><technical_language>fond of .blockLast() in this synchronous method throw exception if a parallel single scheduler... this runs periodically, I more a do this. a reduce number of .blocks using. java final Flux<PartitionOwnership> ownershipFlux = partitionManager.listOwnership(eventHubName, consumerGroupName) .cache(); eventHubAsyncClient.getPartitionIds().flatMap(id -> { return ownershipFlux.filter(ownership -> id.equals(ownership.partitionId())) // Ownership claimed, exist in list, provide a default. .single(new PartitionOwnership().partitionId(id)); }).flatMap(ownershipInfo -> { return partitionManager.claimOwnership(Collections.singletonList(ownershipInfo)).doOnComplete(() -> { logger.info("Claimed ownership"); }).doOnError(error -> { logger.error("Unable claim ownership", error); }); }).blockLast(Duration.ofSeconds(10));</technical_language>

Target:
void run() { final Flux<PartitionOwnership> ownershipFlux = partitionManager.listOwnership(eventHubName, consumerGroupName) .cache(); eventHubAsyncClient.getPartitionIds() .flatMap(id -> getCandidatePartitions(ownershipFlux, id)) .flatMap(this::claimOwnership) .subscribeOn(Schedulers.newElastic("PartitionPumps")) .subscribe(this::receiveEvents); }
Source:
<code>public WptPt toWpt() { WptPt pt = super.toWpt(); pt.getExtensionsToWrite().put(PERSONAL, "true"); <START> pt.name = type.toString(); <END> pt.desc = getDescription(); return pt; }</code><technical_language>type.typeName</technical_language>

Target:
public WptPt toWpt() { WptPt pt = super.toWpt(); pt.getExtensionsToWrite().put(PERSONAL, "true"); pt.name = type.typeName; pt.desc = getDescription(); return pt; }
Source:
<code>public Set<? extends NodeMetadata> suspendNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> suspending nodes matching(%s)", filter); Set<NodeMetadata> set = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminatedExceptionIfNotFound(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { suspendNode(from.getId()); return from; } public String toString() { return "suspendNode(" + from.getId() + ")"; } }); } <START> }, userExecutor, null, logger, "suspendNodesMatching(" + filter + ")")); <END> logger.debug("<< suspended"); cleanUpIncidentalResourcesOfDeadNodes(set); return set; }</code><technical_language>Please fix indenting rename suspendedNodes</technical_language>

Target:
public Set<? extends NodeMetadata> suspendNodesMatching(Predicate<NodeMetadata> filter) { logger.debug(">> suspending nodes matching(%s)", filter); Set<NodeMetadata> suspendNodes = ImmutableSet.copyOf(transformParallel(nodesMatchingFilterAndNotTerminated(filter), new Function<NodeMetadata, ListenableFuture<? extends NodeMetadata>>() { @Override public ListenableFuture<NodeMetadata> apply(final NodeMetadata from) { return userExecutor.submit(new Callable<NodeMetadata>() { public NodeMetadata call() throws Exception { suspendNode(from.getId()); return from; } public String toString() { return "suspendNode(" + from.getId() + ")"; } }); } }, userExecutor, null, logger, "suspendNodesMatching(" + filter + ")")); logger.debug("<< suspended(%d)", suspendNodes.size()); return suspendNodes; }
Source:
<code>public void handlesConnectTimeouts_alwaysRetry() throws IOException, InterruptedException { <START> String urlConnectTimeout = "http:/10.255.255.1"; <END> server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); OkHttpClient client = OkHttpClients.withStableUris( ClientConfiguration.builder() .from(createTestConfig(urlConnectTimeout, url)) .readTimeout(Duration.ofMillis(20)) .maxNumRetries(1) .backoffSlotSize(Duration.ofMillis(10)) .connectTimeout(Duration.ofMillis(50)) .retryOnTimeout(ClientConfiguration.RetryOnTimeout.DISABLED) .build(), AGENT, hostEventsSink, OkHttpClientsTest.class); Call call = client.newCall(new Request.Builder().url(url + "/foo?bar").build()); assertThat(call.execute().body().string()).isEqualTo("foo"); assertThat(server.takeRequest().getPath()).isEqualTo("/foo?bar"); }</code><technical_language>is missing slash intentional</technical_language>

Target:
public void handlesConnectTimeouts_alwaysRetry() throws IOException, InterruptedException { String urlConnectTimeout = "<LINK_0>"; server.enqueue(new MockResponse().setResponseCode(200).setBody("foo")); OkHttpClient client = OkHttpClients.withStableUris( ClientConfiguration.builder() .from(createTestConfig(urlConnectTimeout, url)) .readTimeout(Duration.ofMillis(20)) .maxNumRetries(1) .backoffSlotSize(Duration.ofMillis(10)) .connectTimeout(Duration.ofMillis(50)) .retryOnTimeout(ClientConfiguration.RetryOnTimeout.DISABLED) .build(), AGENT, hostEventsSink, OkHttpClientsTest.class); Call call = client.newCall(new Request.Builder().url(url + "/foo?bar").build()); assertThat(call.execute().body().string()).isEqualTo("foo"); assertThat(server.takeRequest().getPath()).isEqualTo("/foo?bar"); }
Source:
<code>private CharSequence formatTimeLabel(Calendar cal, int strRes) { String label = mRes.getString(strRes); GregorianCalendar tomorrowEOD = new GregorianCalendar(); tomorrowEOD.add(Calendar.DAY_OF_YEAR, 1); tomorrowEOD.set(Calendar.HOUR_OF_DAY, 23); <START> tomorrowEOD.set(Calendar.MINUTE, 59); <END> String time; if (cal.before(tomorrowEOD)) { time = mTimeFormatter.format(cal.getTime()); } else { time = mTimeAndDayFormatter.format(cal.getTime()); } return String.format(label, time); }</code><technical_language>Ugly wrong. End of day tomorrow is defined strictly start of 2 days of today. 23:59:30 break this right now</technical_language>

Target:
private CharSequence formatTimeLabel(Calendar cal, int strRes) { String label = mRes.getString(strRes); GregorianCalendar tomorrowEOD = new GregorianCalendar(); tomorrowEOD.add(Calendar.DAY_OF_YEAR, 2); tomorrowEOD.set(Calendar.HOUR_OF_DAY, 0); tomorrowEOD.set(Calendar.MINUTE, 0); tomorrowEOD.set(Calendar.SECOND, 0); String time; if (cal.before(tomorrowEOD)) { time = mTimeFormatter.format(cal.getTime()); } else { time = mTimeAndDayFormatter.format(cal.getTime()); } return String.format(label, time); }
Source:
<code>public JpaPagingItemReader<WeekActivity> weekActivityReader() { try { String jpqlQuery = "SELECT w FROM WeekActivity w WHERE w.startDate <= :lastWeek AND w.aggregatesComputed = false"; JpaPagingItemReader<WeekActivity> reader = new JpaPagingItemReader<>(); reader.setQueryString(jpqlQuery); reader.setParameterValues(Collections.singletonMap("lastWeek", TimeUtil.getStartOfWeek(ZonedDateTime.now(DEFAULT_TIME_ZONE).toLocalDate()).minusWeeks(1))); reader.setEntityManagerFactory(entityManager.getEntityManagerFactory()); reader.setPageSize(WEEK_ACTIVITY_CHUNK_SIZE); reader.afterPropertiesSet(); reader.setSaveState(true); return reader; } <START> catch (Exception e) <END> { throw YonaException.unexpected(e); } }</code><technical_language>Please change this t a multicatch list of exceptions caught</technical_language>

Target:
public JpaPagingItemReader<WeekActivity> weekActivityReader() { try { String jpqlQuery = "SELECT w FROM WeekActivity w WHERE w.startDate <= :lastWeek AND w.aggregatesComputed = false"; JpaPagingItemReader<WeekActivity> reader = new JpaPagingItemReader<>(); reader.setQueryString(jpqlQuery); reader.setParameterValues(Collections.singletonMap("lastWeek", TimeUtil.getStartOfWeek(ZonedDateTime.now(DEFAULT_TIME_ZONE).minusWeeks(1).toLocalDate()))); reader.setEntityManagerFactory(entityManager.getEntityManagerFactory()); reader.setPageSize(WEEK_ACTIVITY_CHUNK_SIZE); reader.afterPropertiesSet(); reader.setSaveState(true); return reader; } catch (Exception e) { throw YonaException.unexpected(e); } }
Source:
<code>public String getUsages() { <START> return node.getUsages().stream().map(TriggerUsage::name).sorted().collect(Collectors.joining(",")); <END> }</code><technical_language>I exposing Jorje internals arbitrary strings enum dictate usages</technical_language>

Target:
public List<TriggerUsage> getUsages() { return node.getUsages().stream() .map(TriggerUsage::of) .sorted() .collect(Collectors.toList()); }
Source:
<code>public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { <START> final Script cmd = new Script(_ovsTunnelPath, _timeout.getMillis(), s_logger); <END> cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; }</code><technical_language>Please consider adding overridden version of Script(String, int, Logger) constructor accepts Duration encapsulate this type conversion</technical_language>

Target:
public synchronized boolean configureTunnelNetwork(final long networkId, final long hostId, final String nwName) { try { final boolean findResult = findOrCreateTunnelNetwork(nwName); if (!findResult) { s_logger.warn("LibvirtComputingResource.findOrCreateTunnelNetwork() failed! Cannot proceed creating the tunnel."); return false; } final String configuredHosts = Script .runSimpleBashScript("ovs-vsctl get bridge " + nwName + " other_config:ovs-host-setup"); boolean configured = false; if (configuredHosts != null) { final String hostIdsStr[] = configuredHosts.split(","); for (final String hostIdStr : hostIdsStr) { if (hostIdStr.equals(((Long)hostId).toString())) { configured = true; break; } } } if (!configured) { final Script cmd = new Script(_ovsTunnelPath, _timeout, s_logger); cmd.add("setup_ovs_bridge"); cmd.add("--key", nwName); cmd.add("--cs_host_id", ((Long)hostId).toString()); cmd.add("--bridge", nwName); final String result = cmd.execute(); if (result != null) { throw new CloudRuntimeException( "Unable to pre-configure OVS bridge " + nwName + " for network ID:" + networkId); } } } catch (final Exception e) { s_logger.warn("createandConfigureTunnelNetwork failed", e); return false; } return true; }
Source:
<code><START> public void onActivate(ActivateEvent event, EntityRef entity) { <END> EntityRef attackingPlayer = event.getInstigator(); if (attackingPlayer.getComponent(CharacterHeldItemComponent.class).selectedItem.hasComponent(RaycastOnActivateComponent.class)) { if (entity.hasComponent(PlayerCharacterComponent.class)) { blackFlagSlot = searchInventoryForFlag(entity, LASUtils.BLACK_FLAG_URI); if (blackFlagSlot != EntityRef.NULL) { Vector3f position = new Vector3f(entity.getComponent(LocationComponent.class).getLocalPosition()); Vector3f impulseVector = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); entity.send(new DropItemRequest(blackFlagSlot, entity, impulseVector, position)); return; } redFlagSlot = searchInventoryForFlag(entity, LASUtils.RED_FLAG_URI); if (redFlagSlot != EntityRef.NULL) { Vector3f position = new Vector3f(entity.getComponent(LocationComponent.class).getLocalPosition()); Vector3f impulseVector = new Vector3f(attackingPlayer.getComponent(LocationComponent.class).getLocalPosition()); entity.send(new DropItemRequest(redFlagSlot, entity, impulseVector, position)); return; } } } }</code><technical_language>Move this method a method called- dropFlagOnPlayerAttack Pass event EntityRef targetPlayer</technical_language>

Target:
public void onActivate(ActivateEvent event, EntityRef entity) { dropFlagOnPlayerAttack(event, entity); }
Source:
<code>public void test() { channels.input().send(new GenericMessage<Object>("hello")); channels.input().send(new GenericMessage<Object>("hello world")); channels.input().send(new GenericMessage<Object>("hi!")); <START> assertThat(collector.forChannel(channels.output()), receivesPayloadThat(is("hello world"))); <END> }</code><technical_language>add assert for more messages</technical_language>

Target:
public void test() throws InterruptedException { channels.input().send(new GenericMessage<Object>("hello")); channels.input().send(new GenericMessage<Object>("hello world")); channels.input().send(new GenericMessage<Object>("hi!")); assertThat(collector.forChannel(channels.output()), receivesPayloadThat(is("hello world"))); assertThat(collector.forChannel(channels.output()).poll(10, MILLISECONDS), is(nullValue(Message.class))); }
Source:
<code>public Either<java.util.Set<ParseFailedException>, Term> apply(TermCons tc) { if (tc.production().klabel().isDefined() && tc.production().klabel().get().name().equals("#KRewrite")) { <START> String msg = "Due to typing errors, => is not greedy. Use parentheses to set proper scope."; <END> KException kex = new KException(KException.ExceptionType.ERROR, KException.KExceptionGroup.CRITICAL, msg, null, null); return Left.apply(Sets.newHashSet(new PriorityException(kex))); } return Right.apply(tc); }</code><technical_language>here. Needs a error message this error manifest</technical_language>

Target:
public Either<java.util.Set<ParseFailedException>, Term> apply(TermCons tc) { if (tc.production().klabel().isDefined() && tc.production().klabel().get().name().equals("#KRewrite")) { String msg = "Rewrite is not allowed to be an immediate child of " + parent.production().klabel().get() + " Use parentheses: (x)=>(y) to set the proper scope of the operations."; KException kex = new KException(KException.ExceptionType.ERROR, KException.KExceptionGroup.CRITICAL, msg, null, tc.location().get()); return Left.apply(Sets.newHashSet(new PriorityException(kex))); } return Right.apply(tc); }
Source:
<code>private Iterable<ThriftStructFieldInfo> getFieldInfosForUnion(Class klass) { ArrayList<ThriftStructFieldInfo> fields = new ArrayList<ThriftStructFieldInfo>(); for(Field f: klass.getDeclaredFields()){ if (f.getType().equals(Manifest.class)) { Class unionClass = (Class)((ParameterizedType)f.getGenericType()).getActualTypeArguments()[0]; Class companionUnionClass = getCompanionClass(unionClass); try { Object companionUnionObj = companionUnionClass.getField("MODULE$").get(null); ThriftStructFieldInfo info = (ThriftStructFieldInfo)companionUnionClass.getMethod("fieldInfo").invoke(companionUnionObj); fields.add(info); <START> } catch (Exception e) { <END> throw new RuntimeException("can not find fiedInfo for " + unionClass, e); } } } return fields; }</code><technical_language>Exception</technical_language>

Target:
private Iterable<ThriftStructFieldInfo> getFieldInfosForUnion(Class klass) { ArrayList<ThriftStructFieldInfo> fields = new ArrayList<ThriftStructFieldInfo>(); for(Field f: klass.getDeclaredFields()){ if (f.getType().equals(Manifest.class)) { Class unionClass = (Class)((ParameterizedType)f.getGenericType()).getActualTypeArguments()[0]; Class companionUnionClass = getCompanionClass(unionClass); try { Object companionUnionObj = companionUnionClass.getField("MODULE$").get(null); ThriftStructFieldInfo info = (ThriftStructFieldInfo)companionUnionClass.getMethod("fieldInfo").invoke(companionUnionObj); fields.add(info); } catch (ReflectiveOperationException e) { throw new ScroogeSchemaConversionException("can not find fiedInfo for " + unionClass, e); } } } return fields; }
Source:
<code>public void testInvalidFiles() { MappingFile mf = MappingFile.create("test", false); assertNull(mf); <START> Path nmOutput = Paths.get("..", "..", "tmf", "org.eclipse.tracecompass.tmf.core.tests", "testfiles", "callstack" , "emptyFile"); assertTrue(Files.exists(nmOutput)); String filePath = nmOutput.toFile().getAbsolutePath(); assertNotNull(filePath); <END> mf = MappingFile.create(filePath, false); assertNull(mf); }</code><technical_language>This block of code is identical lines 50-54 62-66. create a "retrieveFilePath(...)" method</technical_language>

Target:
public void testInvalidFiles() { IMappingFile mf = IMappingFile.create("test", false); assertNull(mf); mf = getMappingFile("emptyFile"); assertNull(mf); }
Source:
<code>private QNode getOrAddNode() { TaskNode head; QNode headNext; PoolThreadNode newNode = null; for (;;) { head = EnhancedQueueExecutor.this.head; headNext = head.getNext(); if (headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { if (! NO_QUEUE_LIMIT) decreaseQueueSize(); return taskNode; } } else if (headNext instanceof PoolThreadNode || headNext == null) { if (newNode == null) { <START> newNode = new PoolThreadNode(null, Thread.currentThread()); <END> } newNode.setNext(headNext); if (head.compareAndSetNext(headNext, newNode)) { return newNode; } } else { assert headNext instanceof TerminateWaiterNode; return headNext; } if (UPDATE_STATISTICS) spinMisses.increment(); } }</code><technical_language>This constructor is called IIRC, parameter safely dropped instead of null</technical_language>

Target:
private QNode getOrAddNode() { TaskNode head; QNode headNext; PoolThreadNode newNode = null; for (;;) { head = EnhancedQueueExecutor.this.head; headNext = head.getNext(); if (headNext instanceof TaskNode) { TaskNode taskNode = (TaskNode) headNext; if (compareAndSetHead(head, taskNode)) { if (! NO_QUEUE_LIMIT) decreaseQueueSize(); return taskNode; } } else if (headNext instanceof PoolThreadNode || headNext == null) { if (newNode == null) { newNode = new PoolThreadNode(Thread.currentThread()); } newNode.setNext(headNext); if (head.compareAndSetNext(headNext, newNode)) { return newNode; } } else { assert headNext instanceof TerminateWaiterNode; return headNext; } if (UPDATE_STATISTICS) spinMisses.increment(); } }
Source:
<code>private static List<Object> allParameters( TestClass testClass, FrameworkMethod parametersMethod) throws Throwable { Object parameters; try { parameters = parametersMethod.invokeExplosively(null); <START> } catch (AssumptionViolatedException e) { <END> return Collections.<Object>singletonList( new AssumptionViolationRunner(testClass, parametersMethod.getName(), e)); } if (parameters instanceof List) { return (List<Object>) parameters; } else if (parameters instanceof Collection) { return new ArrayList<Object>((Collection<Object>) parameters); } else if (parameters instanceof Iterable) { List<Object> result = new ArrayList<Object>(); for (Object entry : ((Iterable<Object>) parameters)) { result.add(entry); } return result; } else if (parameters instanceof Object[]) { return Arrays.asList((Object[]) parameters); } else { throw parametersMethodReturnedWrongType(testClass, parametersMethod); } }</code><technical_language>catch this exception in caller (RunnersFactory)? If exception caught, set a field in RunnersFactory named runnerOverride a new AssumptionViolationRunner. If runnerOverride is set returned RunnersFactory.createRunners(). a bonus, possibly catch exception there, for exceptions AssumptionViolatedException ErrorReportingRunner</technical_language>

Target:
private static List<Object> allParameters( TestClass testClass, FrameworkMethod parametersMethod) throws Throwable { Object parameters = parametersMethod.invokeExplosively(null); if (parameters instanceof List) { return (List<Object>) parameters; } else if (parameters instanceof Collection) { return new ArrayList<Object>((Collection<Object>) parameters); } else if (parameters instanceof Iterable) { List<Object> result = new ArrayList<Object>(); for (Object entry : ((Iterable<Object>) parameters)) { result.add(entry); } return result; } else if (parameters instanceof Object[]) { return Arrays.asList((Object[]) parameters); } else { throw parametersMethodReturnedWrongType(testClass, parametersMethod); } }
Source:
<code><START> private List<WorkspaceImpl> createEntities(int number) throws TckRepositoryException { <END> List<WorkspaceImpl> wsList = new ArrayList<>(); for (int i = 0; i < number; i++) { wsList.add(new WorkspaceImpl("id" + i, null, null)); } return wsList; }</code><technical_language>this method throw TckRepositoryException</technical_language>

Target:
private List<WorkspaceImpl> createEntities(int number) { List<WorkspaceImpl> wsList = new ArrayList<>(); for (int i = 0; i < number; i++) { wsList.add(new WorkspaceImpl("id" + i, null, null)); } return wsList; }
Source:
<code>private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { Target target = null; for (Target t : availableTargets) { if (t.matches(targetLabel)) { target = t; <START> break; <END> } } if (target == null) { throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); } return target; }</code><technical_language>immediately return target here, simplifying method code</technical_language>

Target:
private Target findMatchingTarget(String targetLabel) throws AndroidContainerConfigurationException { for (Target target : availableTargets) { if (target.matches(targetLabel)) { return target; } } throw new AndroidContainerConfigurationException(String.format("There is not any target with target name '%s'", targetLabel)); }
Source:
<code>public Object execute() throws Exception { return chan.eventLoop().submit(new Runnable() { @Override public void run() }).get(); <START> } <END></code><technical_language>Reuse runnable reduce noise of GC if</technical_language>

Target:
public Object execute() throws Exception { return chan.eventLoop().submit(runnable).get(); }
Source:
<code>protected void tearDownContext() { view.getComputeService().destroyNodesMatching(inGroup(imageGroup)); Optional<? extends Image> image = getImage(); if (image.isPresent() && image.get().getStatus() != Image.Status.DELETED) { Optional<ImageExtension> imageExtension = view.getComputeService().getImageExtension(); if (imageExtension.isPresent()) { imageExtension.get().deleteImage(image.get().getId()); } <START> } <END> super.tearDownContext(); }</code><technical_language>Do need a try...catch this</technical_language>

Target:
protected void tearDownContext() { try { view.getComputeService().destroyNodesMatching(inGroup(imageGroup)); Optional<? extends Image> image = getImage(); if (image.isPresent() && image.get().getStatus() != Image.Status.DELETED) { Optional<ImageExtension> imageExtension = view.getComputeService().getImageExtension(); if (imageExtension.isPresent()) { imageExtension.get().deleteImage(image.get().getId()); } } } catch (Exception e) { } super.tearDownContext(); }
Source:
<code>public void visitAssignmentExpression(AssignmentExpressionTree tree) { AbstractTypedTree variable = (AbstractTypedTree) tree.variable(); <START> if (variable.is(Kind.IDENTIFIER)) { <END> Symbol variableSymbol = getSemanticModel().getReference((IdentifierTree) variable); if (field.equals(variableSymbol)) { addIssue(synchronizedStatement, MessageFormat.format("Don''t synchronize on \"{0}\" or remove its reassignment on line {1}.", field.getName(), String.valueOf(variable.getLine()))); } } }</code><technical_language>trouble: this.myField = "";</technical_language>

Target:
public void visitAssignmentExpression(AssignmentExpressionTree tree) { checkSymbolAssignment((AbstractTypedTree) tree.variable()); }
Source:
<code>private Set<IEntityGroup> getParentGroups(String key, Set<IEntityGroup> groups) { log.debug("Getting parents of group: {}", key); IEntityGroup group = groupsTree.getGroups().get(key); if (group == null) { log.warn("SmartLdap group not found for key: {}", key); return groups; } List<String> parentKeys = groupsTree.getParents().get(key); parentKeys = parentKeys != null ? parentKeys : Collections.emptyList(); log.debug("Parent keys for {}: {}", key, String.join(",", parentKeys)); for (String parentKey : parentKeys) { IEntityGroup parent = groupsTree.getGroups().get(parentKey); if (parent == null) { log.warn("Group tree inconsistent -- missing parent: {}", parentKey); } else if (groups.contains(parent)) { <START> log.warn("Parent found multiple times, could be recursion group tree!"); <END> } else { groups.add(parent); getParentGroups(parentKey, groups); } } return groups; }</code><technical_language>if parent id group id provided log</technical_language>

Target:
private Set<IEntityGroup> getParentGroups(String key, Set<IEntityGroup> groups) { log.debug("Getting parents of group: {}", key); IEntityGroup group = groupsTree.getGroups().get(key); if (group == null) { log.warn("SmartLdap group not found for key: {}", key); return groups; } List<String> parentKeys = groupsTree.getParents().get(key); parentKeys = parentKeys != null ? parentKeys : Collections.emptyList(); log.debug("Parent keys for {}: {}", key, String.join(",", parentKeys)); for (String parentKey : parentKeys) { IEntityGroup parent = groupsTree.getGroups().get(parentKey); if (parent == null) { log.warn("Group tree inconsistent -- missing parent: {}", parentKey); } else if (groups.contains(parent)) { log.warn( "Parent found multiple times, could be recursion group tree! key: {}, parent key: {}", key, parentKey); } else { groups.add(parent); getParentGroups(parentKey, groups); } } return groups; }
Source:
<code>public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } int nextNullRow = nullIterator.next(); if (offset.isContiguous()) { <START> final int startOffset = offset.getStartOffset(); <END> nullIterator.advanceIfNeeded(startOffset); for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; if (row == nextNullRow) { retVal[i] = true; if (nullIterator.hasNext()) { nextNullRow = nullIterator.next(); } else { break; } } else { retVal[i] = false; } } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; if (row == nextNullRow) { retVal[i] = true; if (nullIterator.hasNext()) { nextNullRow = nullIterator.next(); } else { break; } } else { retVal[i] = false; } } } return retVal; }</code><technical_language>I this needs some logic detect offset reset</technical_language>

Target:
public static boolean[] populateNullVector( @Nullable final boolean[] nullVector, final ReadableVectorOffset offset, final PeekableIntIterator nullIterator ) { if (!nullIterator.hasNext()) { return null; } final boolean[] retVal; if (nullVector != null) { retVal = nullVector; } else { retVal = new boolean[offset.getMaxVectorSize()]; } if (offset.isContiguous()) { final int startOffset = offset.getStartOffset(); nullIterator.advanceIfNeeded(startOffset); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = i + startOffset; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { break; } retVal[i] = row == nullIterator.peekNext(); } } else { final int[] currentOffsets = offset.getOffsets(); nullIterator.advanceIfNeeded(currentOffsets[0]); if (!nullIterator.hasNext()) { return null; } for (int i = 0; i < offset.getCurrentVectorSize(); i++) { final int row = currentOffsets[i]; nullIterator.advanceIfNeeded(row); if (!nullIterator.hasNext()) { break; } retVal[i] = row == nullIterator.peekNext(); } } return retVal; }
Source:
<code>public static void startMeasure(final String heading, final String stepName) { LogCollector collector; synchronized (COLLECTOR_POOL) { collector = COLLECTOR_POOL.poll(); } if (null == collector) { <START> collector = new LogCollector(); <END> } LogCollector[] collectors = THREAD_COLLECTORS.get(); final int idxToSet; if (null == collectors) { collectors = new LogCollector[2]; THREAD_COLLECTORS.set(collectors); idxToSet = 0; } else { int freeSlot = -1; for (int idx = 0; idx < collectors.length; ++idx) { if (collectors[idx] == null) { freeSlot = idx; break; } } if (freeSlot < 0) { idxToSet = collectors.length; collectors = Arrays.copyOf(collectors, collectors.length + 2); THREAD_COLLECTORS.set(collectors); } else { idxToSet = freeSlot; } } if (idxToSet > 0) { collectors[idxToSet].addRecord(heading); } collectors[idxToSet] = collector; collector.addRecord(heading); collector.addRecord(stepName); }</code><technical_language>threads reused servlet container, sense clean thread local finish measurements</technical_language>

Target:
public static void startMeasure(final String heading, final String stepName) { final LogCollector collector = new LogCollector(); List<LogCollector> collectors = THREAD_COLLECTORS.get(); if (null == collectors) { collectors = new ArrayList<>(2); THREAD_COLLECTORS.set(collectors); } if (!collectors.isEmpty()) { collectors.get(collectors.size() - 1).addRecord(heading); } collectors.add(collector); collector.addRecord(heading); collector.addRecord(stepName); }