auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void assertValidType( String key, Object value, IndexIdentifier identifier ) { DocValuesType expectedType; String expectedTypeName; if ( value instanceof Number ) { expectedType = DocValuesType.SORTED_NUMERIC; expectedTypeName = "numbers"; } else { expectedType = DocValuesType.SORTED_SET; expectedTypeName = "strings"; } <START> Map<String,DocValuesType> stringDocValuesTypeMap = indexTypeMap.get( identifier ); <END> if ( stringDocValuesTypeMap == null ) { getIndexSearcher( identifier ); stringDocValuesTypeMap = indexTypeMap.get( identifier ); } DocValuesType actualType; synchronized ( stringDocValuesTypeMap ) { actualType = stringDocValuesTypeMap.get( key ); if ( actualType == null ) { actualType = expectedType; stringDocValuesTypeMap.put( key, expectedType ); } } if ( !actualType.equals( expectedType ) ) { throw new IllegalArgumentException( String.format( "Cannot index '%s' for key '%s', since this key has been used to index another %s.", value, key, expectedTypeName ) ); } }</code><technical_language>indexTypeMap.computeIfAbsent</technical_language>

Target:
public void assertValidType( String key, Object value, IndexIdentifier identifier ) { DocValuesType expectedType; String expectedTypeName; if ( value instanceof Number ) { expectedType = DocValuesType.SORTED_NUMERIC; expectedTypeName = "numbers"; } else { expectedType = DocValuesType.SORTED_SET; expectedTypeName = "strings"; } Map<String,DocValuesType> stringDocValuesTypeMap = indexTypeMap.get( identifier ); if ( stringDocValuesTypeMap == null ) { getIndexSearcher( identifier ); stringDocValuesTypeMap = indexTypeMap.get( identifier ); } DocValuesType actualType; actualType = stringDocValuesTypeMap.putIfAbsent( key, expectedType ); if ( actualType != null && !actualType.equals( expectedType ) ) { throw new IllegalArgumentException( String.format( "Cannot index '%s' for key '%s', since this key has been used to index another %s.", value, key, expectedTypeName ) ); } }
Source:
<code>public ForumList getForums(String communityUuid, Map<String, String> parameters) throws CommunityServiceException { if (StringUtil.isEmpty(communityUuid)){ throw new CommunityServiceException(null, Messages.NullCommunityIdException); } if(null == parameters){ parameters = new HashMap<String, String>(); } parameters.put(COMMUNITY_UNIQUE_IDENTIFIER, communityUuid); <START> ForumList forums = null; <END> try { ForumService svc = new ForumService(this.endpoint); forums = svc.getAllForums(parameters); }catch (Exception e) { throw new CommunityServiceException(e, Messages.CommunityForumTopicsException, communityUuid); } return forums; }</code><technical_language>Do need this null</technical_language>

Target:
public ForumList getForums(String communityUuid, Map<String, String> parameters) throws CommunityServiceException { if (StringUtil.isEmpty(communityUuid)){ throw new CommunityServiceException(null, Messages.NullCommunityIdException); } if(null == parameters){ parameters = new HashMap<String, String>(); } parameters.put(COMMUNITY_UNIQUE_IDENTIFIER, communityUuid); ForumList forums; try { ForumService svc = new ForumService(this.endpoint); forums = svc.getAllForums(parameters); }catch (Exception e) { throw new CommunityServiceException(e, Messages.CommunityForumTopicsException, communityUuid); } return forums; }
Source:
<code>public void shouldResumeWhenWritabilityChanged() throws Exception { TransportThrottle throttle = newThrottleAndInstall( channel ); when( channel.isWritable() ).thenReturn( false ); Future future = Executors.newSingleThreadExecutor().submit( () -> throttle.acquire( channel ) ); <START> Thread.sleep( 500 ); <END> when( channel.isWritable() ).thenReturn( true ); ArgumentCaptor<ChannelInboundHandler> captor = ArgumentCaptor.forClass( ChannelInboundHandler.class ); verify( channel.pipeline() ).addLast( captor.capture() ); captor.getValue().channelWritabilityChanged( context ); try { future.get( 2000, TimeUnit.MILLISECONDS ); } catch ( Throwable t ) { fail( "should not throw" ); } verify( lock, atLeastOnce() ).lock( any(), anyLong() ); verify( lock, times( 1 ) ).unlock( any() ); }</code><technical_language>Sleep this test flaky. ok do future.get() instead</technical_language>

Target:
public void shouldResumeWhenWritabilityChanged() throws Exception { TransportThrottle throttle = newThrottleAndInstall( channel ); when( channel.isWritable() ).thenReturn( false ); Future future = Executors.newSingleThreadExecutor().submit( () -> throttle.acquire( channel ) ); if ( !lock.waitLocked( 1, TimeUnit.SECONDS ) ) { fail( "lock should be acquired" ); } when( channel.isWritable() ).thenReturn( true ); ArgumentCaptor<ChannelInboundHandler> captor = ArgumentCaptor.forClass( ChannelInboundHandler.class ); verify( channel.pipeline() ).addLast( captor.capture() ); captor.getValue().channelWritabilityChanged( context ); try { future.get( 2000, TimeUnit.MILLISECONDS ); } catch ( Throwable t ) { fail( "should not throw" ); } assertThat( lock.lockCallCount(), greaterThan( 0 ) ); assertThat( lock.unlockCallCount(), is( 1 ) ); }
Source:
<code>private static boolean isExternal(File directory) { boolean state = false; String cacheDirPath = null; File extStoragePath = Environment.getExternalStorageDirectory(); <START> if(extStoragePath != null) { <END> cacheDirPath = extStoragePath.toString(); try { String appCacheDirPath = directory.getCanonicalPath(); if (appCacheDirPath.contains(cacheDirPath)) state = true; } catch (IOException e) { e.printStackTrace(); } }else{ state = false;} return state; }</code><technical_language>Nit: coding style, add spaces keywords</technical_language>

Target:
private static boolean isExternal(File directory) { boolean state = false; String cacheDirPath = null; File extStoragePath = Environment.getExternalStorageDirectory(); if(extStoragePath != null) { cacheDirPath = extStoragePath.toString(); try { String appCacheDirPath = directory.getCanonicalPath(); if (appCacheDirPath.contains(cacheDirPath)) { state = true;} } catch (IOException e) { e.printStackTrace(); } } return state; }
Source:
<code>public void map() throws Exception { PinotSegmentRecordReader segmentRecordReader = new PinotSegmentRecordReader(_inputSegment); GenericRow reusableRow = new GenericRow(); <START> GenericData.Record reusableRecord = new GenericData.Record(_avroSchema); <END> Set<String> selectedPartitions = new HashSet<>(); Set<String> rejectedPartitions = new HashSet<>(); while (segmentRecordReader.hasNext()) { reusableRow = segmentRecordReader.next(reusableRow); reusableRow = _recordTransformer.transformRecord(reusableRow); String partition = _partitioner.getPartition(reusableRow); if (rejectedPartitions.contains(partition)) { continue; } if (!selectedPartitions.contains(partition)) { boolean filter = _partitionFilter.filter(partition); if (filter) { rejectedPartitions.add(partition); continue; } else { selectedPartitions.add(partition); } } if (!_partitionToDataFileWriterMap.containsKey(partition)) { File partDir = new File(_mapperOutputDir, partition); if (!partDir.exists()) { Files.createDirectory(Paths.get(partDir.getAbsolutePath())); } DataFileWriter<GenericData.Record> recordWriter = new DataFileWriter<>(new GenericDatumWriter<>(_avroSchema)); recordWriter.create(_avroSchema, new File(partDir, createMapperOutputFileName(_mapperId))); _partitionToDataFileWriterMap.put(partition, recordWriter); } SegmentProcessorUtils.convertGenericRowToAvroRecord(reusableRow, reusableRecord); _partitionToDataFileWriterMap.get(partition).append(reusableRecord); } }</code><technical_language>interface out underlying data file format? need plug in other data format for performance boost (for example, @Jackie-Jiang mmaped file custom format for star-tree generator similar work - sort, aggregation)</technical_language>

Target:
public void map() throws Exception { PinotSegmentRecordReader segmentRecordReader = new PinotSegmentRecordReader(_inputSegment); GenericRow reusableRow = new GenericRow(); GenericData.Record reusableRecord = new GenericData.Record(_avroSchema); while (segmentRecordReader.hasNext()) { reusableRow = segmentRecordReader.next(reusableRow); reusableRow = _recordTransformer.transformRecord(reusableRow); if (_recordFilter.filter(reusableRow)) { continue; } String partition = _partitioner.getPartition(reusableRow); DataFileWriter<GenericData.Record> recordWriter = _partitionToDataFileWriterMap.get(partition); if (recordWriter == null) { File partDir = new File(_mapperOutputDir, partition); if (!partDir.exists()) { Files.createDirectory(Paths.get(partDir.getAbsolutePath())); } recordWriter = new DataFileWriter<>(new GenericDatumWriter<>(_avroSchema)); recordWriter.create(_avroSchema, new File(partDir, createMapperOutputFileName(_mapperId))); _partitionToDataFileWriterMap.put(partition, recordWriter); } SegmentProcessorUtils.convertGenericRowToAvroRecord(reusableRow, reusableRecord); recordWriter.append(reusableRecord); } }
Source:
<code>protected JobPartTrackerDecorator(final List<Objects> chunks, final EventRunner eventRunner) { <START> clientJobPartTracker = JobPartTrackerFactory.buildPartTracker(Iterables.concat(getAllBlobApiBeans(chunks)), eventRunner); <END> internalJobPartTracker = JobPartTrackerFactory.buildPartTracker(Iterables.concat(getAllBlobApiBeans(chunks)), eventRunner); }</code><technical_language>Is Iterables.concat required here</technical_language>

Target:
protected JobPartTrackerDecorator(final List<Objects> chunks, final EventRunner eventRunner) { clientJobPartTracker = JobPartTrackerFactory.buildPartTracker(getAllBlobApiBeans(chunks), eventRunner); internalJobPartTracker = JobPartTrackerFactory.buildPartTracker(getAllBlobApiBeans(chunks), eventRunner); }
Source:
<code>public void prepareRun(BatchAggregatorContext context) throws Exception { <START> setNumPartitions(context, dedupConfig.numPartitions); <END> if (SchemaValidator.canRecordLineage(context.getOutputSchema(), "output")) { TransformLineageRecorderUtils.generateOneToOnes( TransformLineageRecorderUtils.getFields(context.getInputSchema()), "dedup", "Removed duplicate records based on unique fields."); } }</code><technical_language>remove this in case in future some common class is constructed for prepareRun() method</technical_language>

Target:
public void prepareRun(BatchAggregatorContext context) throws Exception { super.prepareRun(context); if (SchemaValidator.canRecordLineage(context.getOutputSchema(), context.getStageName())) { TransformLineageRecorderUtils.generateOneToOnes( TransformLineageRecorderUtils.getFields(context.getInputSchema()), "dedup", "Removed duplicate records based on unique fields."); } }
Source:
<code>public void visitMethodInvocation(MethodInvocationTree tree) { if (SUPER_THREAD.matches(tree) && ThreadOverridesRunCheck.hasRunnableArgument(tree.arguments())) { <START> callSuperWithRunnable = true; <END> } super.visitMethodInvocation(tree); }</code><technical_language>micro optimisation : need visit further..</technical_language>

Target:
public void visitMethodInvocation(MethodInvocationTree tree) { if (SUPER_THREAD.matches(tree) && ThreadOverridesRunCheck.hasRunnableArgument(tree.arguments())) { callSuperWithRunnable = true; return; } super.visitMethodInvocation(tree); }
Source:
<code>private int compileShader(int type, Set<ShaderProgramFeature> features) { int shaderId = GL20.glCreateShader(type); String shader = createShader(type, features); <START> Config config = CoreRegistry.get(Config.class); <END> if (config.getRendering().isDumpShaders()) { dumpCode(type, features, shader); } GL20.glShaderSource(shaderId, shader); GL20.glCompileShader(shaderId); int featureHash = ShaderProgramFeature.getBitset(features); if (type == GL20.GL_FRAGMENT_SHADER) { fragmentPrograms.put(featureHash, shaderId); } else if (type == GL20.GL_VERTEX_SHADER) { vertexPrograms.put(featureHash, shaderId); } return shaderId; }</code><technical_language>renderingConfig renderingDebugConfig obtained reobtained CoreRegistry class. get once, a couple of variables those</technical_language>

Target:
private int compileShader(int type, Set<ShaderProgramFeature> features) { int shaderId = GL20.glCreateShader(type); String shader = assembleShader(type, features); if (config.getRendering().isDumpShaders()) { dumpCode(type, features, shader); } GL20.glShaderSource(shaderId, shader); GL20.glCompileShader(shaderId); return shaderId; }
Source:
<code>protected Query complete(Criteria criteria, Sort sort) { <START> Criteria toUse = null; <END> if (accessor.getSampleObject() != null) { toUse = new Criteria().alike(accessor.getSampleObject()); } if (criteria != null) { if (toUse == null) { toUse = criteria; } else { toUse.andOperator(criteria); } } Query query = (toUse == null ? new Query() : new Query(toUse)).with(sort); if (LOG.isDebugEnabled()) { LOG.debug("Created query " + query); } return query; }</code><technical_language>changes necessary anymore (deletion applies)</technical_language>

Target:
protected Query complete(Criteria criteria, Sort sort) { Query query = (criteria == null ? new Query() : new Query(criteria)).with(sort); if (LOG.isDebugEnabled()) { LOG.debug("Created query " + query); } return query; }
Source:
<code>private boolean checkPermission(final Subject subject, final Permission permission, String errorMessage) throws PermissionException { try { Subject.doAsPrivileged(subject, new PrivilegedAction<Object>() { <START> public Object run() { <END> SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(permission); } return null; } }, null); } catch (SecurityException ex) { throw new PermissionException(errorMessage); } return true; }</code><technical_language>I replace this Lambda</technical_language>

Target:
private boolean checkPermission(final Subject subject, final Permission permission, String errorMessage) throws PermissionException { try { Subject.doAsPrivileged(subject, (PrivilegedAction<Object>) () -> { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPermission(permission); } return null; }, null); } catch (SecurityException ex) { throw new PermissionException(errorMessage); } return true; }
Source:
<code>public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); relationshipDelete( relId ); <START> count.increment(); <END> } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }</code><technical_language>If previous semantic, increment count if relationshipDelete returns true</technical_language>

Target:
public int nodeDetachDelete( final long nodeId ) throws KernelException { final MutableInt count = new MutableInt(); TwoPhaseNodeForRelationshipLocking locking = new TwoPhaseNodeForRelationshipLocking( relId -> { ktx.assertOpen(); if ( relationshipDelete( relId ) ) { count.increment(); } } ); locking.lockAllNodesAndConsumeRelationships( nodeId, ktx ); ktx.assertOpen(); nodeDelete( nodeId ); return count.intValue(); }
Source:
<code>public void nodeChildrenChanged(final String path) { waitUntilStarted(); if (path.equals(aclZNode)) { if (childrenChangedFuture != null && !childrenChangedFuture.isDone()) { boolean cancelled = childrenChangedFuture.cancel(true); if (!cancelled) { if (!childrenChangedFuture.isDone()) { LOG.warn("Could not cancel processing node children changed event, " + "please file a JIRA and attach logs if possible."); } } } childrenChangedFuture = asyncProcessNodeUpdate(() -> { try { final List<ZKUtil.NodeAndData> nodeList = ZKUtil.getChildDataAndWatchForNewChildren(watcher, aclZNode); refreshNodes(nodeList); } catch (KeeperException ke) { <START> LOG.error("Error reading data from zookeeper for path " + path, ke); <END> watcher.abort("ZooKeeper error get node children for path " + path, ke); } }); } }</code><technical_language>Please user for LOG param path</technical_language>

Target:
public void nodeChildrenChanged(final String path) { waitUntilStarted(); if (path.equals(aclZNode)) { if (childrenChangedFuture != null && !childrenChangedFuture.isDone()) { boolean cancelled = childrenChangedFuture.cancel(true); if (!cancelled) { if (!childrenChangedFuture.isDone()) { LOG.warn("Could not cancel processing node children changed event, " + "please file a JIRA and attach logs if possible."); } } } childrenChangedFuture = asyncProcessNodeUpdate(() -> { try { final List<ZKUtil.NodeAndData> nodeList = ZKUtil.getChildDataAndWatchForNewChildren(watcher, aclZNode); refreshNodes(nodeList); } catch (KeeperException ke) { String msg = "ZooKeeper error while reading node children data for path " + path; LOG.error(msg, ke); watcher.abort(msg, ke); } }); } }
Source:
<code>public boolean conforms() { <START> return ((in().numDimensions() == 2) || ((in().numDimensions() == 3) && (in().dimension(2) == 3))); <END> }</code><technical_language>is this a requirement in().dimension(2)==3? work for arbitrary dims, right</technical_language>

Target:
public boolean conforms() { return ((in().numDimensions() == 2) || (in().numDimensions() == 3)); }
Source:
<code>public void onReceive(final Object message) throws Exception { if ("tick".equals(message)) { LOGGER.trace() .setMessage("Searching for added/updated hosts") .addData("actor", self()) .log(); <START> LOGGER.debug() <END> .setMessage("Calling Foreman API to get hosts") .log(); Patterns.pipe(_client.getHostPage(1).wrapped(), context().dispatcher()).to(self(), self()); } else if (message instanceof ForemanClient.HostPageResponse) { final ForemanClient.HostPageResponse response = (ForemanClient.HostPageResponse) message; final List<ForemanClient.ForemanHost> results = response.getResults(); for (ForemanClient.ForemanHost host : results) { final Host dh = new DefaultHost.Builder() .setHostname(host.getName()) .setMetricsSoftwareState(MetricsSoftwareState.UNKNOWN) .build(); _hostRepository.addOrUpdateHost(dh); } if (response.getTotal() > response.getPage() * response.getPerPage()) { Patterns.pipe(_client.getHostPage(response.getPage() + 1, response.getPerPage()).wrapped(), context().dispatcher()) .to(self(), self()); } } else { LOGGER.warn() .setMessage("unhandled message") .addData("akkaMessage", message) .log(); unhandled(message); } }</code><technical_language>This double log weird. other in host provider itself</technical_language>

Target:
public void onReceive(final Object message) throws Exception { if (TICK.equals(message)) { LOGGER.trace() .setMessage("Searching for added/updated hosts") .addData("actor", self()) .log(); Patterns.pipe(_client.getHostPage(1).wrapped(), context().dispatcher()).to(self(), self()); } else if (message instanceof ForemanClient.HostPageResponse) { final ForemanClient.HostPageResponse response = (ForemanClient.HostPageResponse) message; final List<ForemanClient.ForemanHost> results = response.getResults(); for (final ForemanClient.ForemanHost host : results) { final Host dh = new DefaultHost.Builder() .setHostname(host.getName()) .setMetricsSoftwareState(MetricsSoftwareState.UNKNOWN) .build(); _hostRepository.addOrUpdateHost(dh); } if (response.getTotal() > response.getPage() * response.getPerPage()) { Patterns.pipe(_client.getHostPage(response.getPage() + 1, response.getPerPage()).wrapped(), context().dispatcher()) .to(self(), self()); } } else { LOGGER.warn() .setMessage("unhandled message") .addData("akkaMessage", message) .log(); unhandled(message); } }
Source:
<code>public void testIsValid() { <START> ZoneOffset offset = ZoneOffset.ofHours( 8 ); <END> OffsetTime future = OffsetTime.now( offset ).plusHours( 1 ); OffsetTime past = OffsetTime.now( offset ).minusHours( 1 ); assertTrue( constraint.isValid( null, null ) ); assertTrue( constraint.isValid( past, null ) ); assertFalse( constraint.isValid( future, null ) ); }</code><technical_language>zone offset? I this is test fails. For test instances a zone offset of 8 _OffsetTime.now( ZoneId )_, in validator default time zone _OffsetTime.now_</technical_language>

Target:
public void testIsValid() { assertTrue( constraint.isValid( null, null ), "null fails validation." ); for ( int i = -18; i <= 18; i++ ) { ZoneOffset offset = ZoneOffset.ofHours( i ); OffsetTime now = OffsetTime.now( offset ); int currentHour = now.getHour(); int currentMinute = now.getMinute(); OffsetTime future = now.plusMinutes( 1 ); OffsetTime past = now.minusMinutes( 1 ); if (!(currentHour == 0 && currentMinute == 0)) { assertTrue( constraint.isValid( past, null ), "Past OffsetTime '" + past + "' fails validation."); } if (!(currentHour == 23 && currentMinute == 59)) { assertFalse( constraint.isValid( future, null ), "Future OffsetTime '" + future + "' validated as past."); } } }
Source:
<code>public PolicyEventMapper() { this(null); nextEventIdCtxResolver = new EventInternalContextResolver<>(POLICY_NEXT_EVENT_CTX_IDS, <START> () -> Collections.emptySet()); <END> }</code><technical_language>static import</technical_language>

Target:
public PolicyEventMapper() { this(null); nextEventIdCtxResolver = new EventInternalContextResolver<>(POLICY_NEXT_EVENT_CTX_IDS, () -> emptySet()); }
Source:
<code>public long countAllCheckTestEntries(final Integer studyId, final String programUuid, final Boolean checkOnly) { final List<Enumeration> entryTypes = this.entryTypeService.getEntryTypes(programUuid); if(checkOnly) { return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, Collections.singletonList(String.valueOf(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()))); } else { final List<String> checkEntryTypeIds = entryTypes.stream() <START> .filter(enttryType -> enttryType.getId() != SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId()) <END> .map(entryType -> String.valueOf(entryType.getId())).collect(Collectors.toList()); return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, checkEntryTypeIds); } }</code><technical_language>typo enttryType @mderamos</technical_language>

Target:
public long countAllCheckTestEntries(final Integer studyId, final String programUuid, final Boolean checkOnly) { final List<Enumeration> entryTypes = this.entryTypeService.getEntryTypes(programUuid); if(checkOnly) { return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, Collections.singletonList(String.valueOf(SystemDefinedEntryType.CHECK_ENTRY.getEntryTypeCategoricalId()))); } else { final List<String> checkEntryTypeIds = entryTypes.stream() .filter(entryType -> entryType.getId() != SystemDefinedEntryType.TEST_ENTRY.getEntryTypeCategoricalId()) .map(entryType -> String.valueOf(entryType.getId())).collect(Collectors.toList()); return this.middlewareStudyEntryService.countStudyGermplasmByEntryTypeIds(studyId, checkEntryTypeIds); } }
Source:
<code>private static DiskImage createDiskImage() { DiskImage disk = new DiskImage(); disk.setId(diskId); <START> disk.setStorageIds(new ArrayList<Guid>(Arrays.asList(storageId))); <END> return disk; }</code><technical_language>Collections.singleton instead of Arrays.asList</technical_language>

Target:
private DiskImage createDiskImage() { DiskImage disk = new DiskImage(); disk.setId(diskId); Collections.singletonList(storageId); disk.setStorageIds(new ArrayList<Guid>(Collections.singletonList(storageId))); return disk; }
Source:
<code><START> public Tuple<Optional<String>, Lock> resolveEvalWithLock(final int blockId) { <END> checkInitialization(); waitBlockMigrationTobeFinished(blockId); final Lock readLock = routerLock.readLock(); readLock.lock(); final int memoryStoreId = blockLocations.get(blockId); if (memoryStoreId == localStoreId) { return new Tuple<>(Optional.empty(), readLock); } else { return new Tuple<>(Optional.of(getEvalId(memoryStoreId)), readLock); } }</code><technical_language>org.apache.commons.lang3.tuple.Pair instead, is more general</technical_language>

Target:
public Tuple<Optional<String>, Lock> resolveEvalWithLock(final int blockId) { checkInitialization(); waitBlockMigrationToEnd(blockId); final Lock readLock = routerLock.readLock(); readLock.lock(); final int memoryStoreId = blockLocations.get(blockId); if (memoryStoreId == localStoreId) { return new Tuple<>(Optional.empty(), readLock); } else { return new Tuple<>(Optional.of(getEvalId(memoryStoreId)), readLock); } }
Source:
<code>private boolean anyFileVideoPreviewing() { <START> final HookActivity activity = (HookActivity) mContext; <END> Fragment secondFragment = activity.getSupportFragmentManager().findFragmentByTag( TAG_SECOND_FRAGMENT); boolean videoPreviewing = false; if (secondFragment instanceof PreviewVideoFragment) { for (int i=0; !videoPreviewing && i < mFiles.size(); i++) { videoPreviewing = ((PreviewVideoFragment) secondFragment) .isFileToPreview(mFiles.get(i)); } }; return videoPreviewing; }</code><technical_language>Casting HookActivity is needed, FragmentActivity instead. need cast is bad enough itself, do general class least</technical_language>

Target:
private boolean anyFileVideoPreviewing() { final FragmentActivity activity = (FragmentActivity) mContext; Fragment secondFragment = activity.getSupportFragmentManager().findFragmentByTag( TAG_SECOND_FRAGMENT); boolean videoPreviewing = false; if (secondFragment instanceof PreviewVideoFragment) { for (int i=0; !videoPreviewing && i < mFiles.size(); i++) { videoPreviewing = ((PreviewVideoFragment) secondFragment). getFile().equals(mFiles.get(i)); } }; return videoPreviewing; }
Source:
<code>public ObservationDto() { <START> super(); <END> }</code><technical_language>a superclass</technical_language>

Target:
public ObservationDto() { }
Source:
<code>public void testGetBorderPlanetsFactionBorders() { DateTime when = new DateTime(); List<Planet> planets = new ArrayList<>(); for (int x = -3; x <= 3; x += 2) { for (int y = -2; y <= 2; y += 2) { planets.add(createPlanet(x, y, factionThem)); } } planets.add(createPlanet(0, 0, factionUs)); FactionBorders us = new FactionBorders(factionUs, when, planets); FactionBorders them = new FactionBorders(factionThem, when, planets); List<Planet> border = us.getBorderPlanets(them, 1.1); assertEquals(border.size(), 2); for (Planet p : border) { <START> assertEquals(Math.abs(p.getX()), 1, 0.001); <END> assertEquals(p.getY(), 0, 0.001); } }</code><technical_language>RegionPerimeter.EPSILON</technical_language>

Target:
public void testGetBorderPlanetsFactionBorders() { DateTime when = new DateTime(); List<Planet> planets = new ArrayList<>(); for (int x = -3; x <= 3; x += 2) { for (int y = -2; y <= 2; y += 2) { planets.add(createPlanet(x, y, factionThem)); } } planets.add(createPlanet(0, 0, factionUs)); FactionBorders us = new FactionBorders(factionUs, when, planets); FactionBorders them = new FactionBorders(factionThem, when, planets); List<Planet> border = us.getBorderPlanets(them, 1.1); assertEquals(border.size(), 2); for (Planet p : border) { assertEquals(Math.abs(p.getX()), 1, RegionPerimeter.EPSILON); assertEquals(p.getY(), 0, RegionPerimeter.EPSILON); } }
Source:
<code>public String readUTF() { int utflen = readInt(); byte[] bytearr = bytes; char[] chararr = new char[utflen]; utflen = pos + utflen; int c, char2, char3; int count = pos; int chararr_count=0; while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++]=(char)c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: count++; chararr[chararr_count++]=(char)c; break; case 12: case 13: count += 2; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-1]; if ((char2 & 0xC0) != 0x80) throw new RuntimeException( "malformed input around byte " + count); chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: count += 3; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-2]; char3 = (int) bytearr[count-1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new RuntimeException( "malformed input around byte " + (count-1)); chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | <START> ((char3 & 0x3F) << 0)); <END> break; default: throw new RuntimeException( "malformed input around byte " + count); } } pos = count; return new String(chararr, 0, chararr_count); }</code><technical_language>This simplified (char3 & 0x3F)</technical_language>

Target:
public String readUTF() { int utflen = readInt(); byte[] bytearr = bytes; char[] chararr = new char[utflen]; utflen = pos + utflen; int c, char2, char3; int count = pos; int chararr_count=0; while (count < utflen) { c = (int) bytearr[count] & 0xff; if (c > 127) break; count++; chararr[chararr_count++]=(char)c; } while (count < utflen) { c = (int) bytearr[count] & 0xff; switch (c >> 4) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: count++; chararr[chararr_count++]=(char)c; break; case 12: case 13: count += 2; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-1]; if ((char2 & 0xC0) != 0x80) throw new RuntimeException( "malformed input around byte " + count); chararr[chararr_count++]=(char)(((c & 0x1F) << 6) | (char2 & 0x3F)); break; case 14: count += 3; if (count > utflen) throw new RuntimeException( "malformed input: partial character at end"); char2 = (int) bytearr[count-2]; char3 = (int) bytearr[count-1]; if (((char2 & 0xC0) != 0x80) || ((char3 & 0xC0) != 0x80)) throw new RuntimeException( "malformed input around byte " + (count-1)); chararr[chararr_count++]=(char)(((c & 0x0F) << 12) | ((char2 & 0x3F) << 6) | (char3 & 0x3F)); break; default: throw new RuntimeException( "malformed input around byte " + count); } } pos = count; return new String(chararr, 0, chararr_count); }
Source:
<code>public synchronized BinaryDequeReader openForRead(String cursorId) throws IOException { if (m_closed) { throw new IOException("Closed"); } <START> if (!m_readCursors.containsKey(cursorId)) { <END> ReadCursor cursor = new ReadCursor(cursorId); m_readCursors.put(cursorId, cursor); persistCursor(cursorId); } return m_readCursors.get(cursorId); }</code><technical_language>readCursors null entry? if not, another map lookup saved calling get() first</technical_language>

Target:
public synchronized BinaryDequeReader openForRead(String cursorId) throws IOException { if (m_closed) { throw new IOException("Closed"); } ReadCursor reader = m_readCursors.get(cursorId); if (reader == null) { reader = new ReadCursor(cursorId, m_numDeleted); m_readCursors.put(cursorId, reader); persistCursor(cursorId); } return reader; }
Source:
<code>public static ObjectId read(InputStream in) throws IOException { byte marker = (byte) in.read(); switch (marker) { case NULL_MARKER: return null; case NON_NULL_MARKER: <START> final byte[] b = new byte[OBJECT_ID_LENGTH]; <END> IO.readFully(in, b, 0, OBJECT_ID_LENGTH); return ObjectId.fromRaw(b); default: throw new IOException("Invalid flag before ObjectId: " + marker); } }</code><technical_language>optional: likewise, call readWithoutMarker</technical_language>

Target:
public static ObjectId read(InputStream in) throws IOException { byte marker = (byte) in.read(); switch (marker) { case NULL_MARKER: return null; case NON_NULL_MARKER: return readWithoutMarker(in); default: throw new IOException("Invalid flag before ObjectId: " + marker); } }
Source:
<code>public void nonBinaryNoSourceImages() throws Exception { CollectionObject collObject = repoObjectFactory.createCollectionObject(null); final Map<String, Object> headers = createEvent(false, collObject.getPid(), Cdr.Collection.getURI(), Container.getURI()); template.sendBodyAndHeaders("", headers); NotifyBuilder notify1 = new NotifyBuilder(cdrEnhancements) .whenCompleted(1) .create(); boolean result1 = notify1.matches(5l, TimeUnit.SECONDS); assertTrue("Enhancement route not satisfied", result1); verify(addSmallThumbnailProcessor, never()).process(any(Exchange.class)); <START> verify(addLargeThumbnailProcessor, never()).process(any(Exchange.class)); <END> }</code><technical_language>solr ingest processor run in this case, if a bug</technical_language>

Target:
public void nonBinaryNoSourceImages() throws Exception { CollectionObject collObject = repoObjectFactory.createCollectionObject(null); final Map<String, Object> headers = createEvent(collObject.getPid(), Cdr.Collection.getURI(), Container.getURI()); template.sendBodyAndHeaders("", headers); NotifyBuilder notify1 = new NotifyBuilder(cdrEnhancements) .whenCompleted(1) .create(); boolean result1 = notify1.matches(5l, TimeUnit.SECONDS); assertTrue("Enhancement route not satisfied", result1); verify(addSmallThumbnailProcessor, never()).process(any(Exchange.class)); verify(addLargeThumbnailProcessor, never()).process(any(Exchange.class)); verify(solrIngestProcessor).process(any(Exchange.class)); }
Source:
<code>private void addStyles() { importGlusterConfigurationEditor.addContentWidgetStyleName(style.editorContentWidget()); migrateOnErrorOption_NOEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_YESEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_HA_ONLYEditor.addContentWidgetStyleName(style.label()); <START> optimizationNoneEditor.setContentWidgetStyleName(style.radioButtonPositioning()); <END> optimizationForServerEditor.setContentWidgetStyleName(style.radioButtonPositioning()); optimizationForDesktopEditor.setContentWidgetStyleName(style.radioButtonPositioning()); optimizationCustomEditor.setContentWidgetStyleName(style.radioButtonPositioning()); countThreadsAsCoresEditor.setContentWidgetStyleName(style.fullWidth()); enableTrustedServiceEditor.setContentWidgetStyleName(style.fullWidth()); }</code><technical_language>I spacing rows of radio button increased, spacing radio buttons, I understand Einav's intention. set style of entire widget? Also, removing fullWidth style trouble</technical_language>

Target:
private void addStyles() { importGlusterConfigurationEditor.addContentWidgetStyleName(style.editorContentWidget()); migrateOnErrorOption_NOEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_YESEditor.addContentWidgetStyleName(style.label()); migrateOnErrorOption_HA_ONLYEditor.addContentWidgetStyleName(style.label()); countThreadsAsCoresEditor.setContentWidgetStyleName(style.fullWidth()); enableTrustedServiceEditor.setContentWidgetStyleName(style.fullWidth()); }
Source:
<code><START> public void testToCompletionStageTrampolining() { <END> waitFor(2); Thread mainThread = Thread.currentThread(); Future<String> success = Future.succeededFuture("Yo"); success.toCompletionStage() .thenAccept(str -> { assertEquals("Yo", str); assertSame(mainThread, Thread.currentThread()); complete(); }); Future<String> failed = Future.failedFuture(new RuntimeException("Woops")); failed.toCompletionStage() .whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertSame(mainThread, Thread.currentThread()); complete(); }); await(5, SECONDS); }</code><technical_language>mandatory save some duplication refactoring tests</technical_language>

Target:
public void testToCompletionStageTrampolining() { waitFor(2); Thread mainThread = Thread.currentThread(); Future<String> success = Future.succeededFuture("Yo"); success.toCompletionStage() .thenAccept(str -> { assertEquals("Yo", str); assertSame(mainThread, Thread.currentThread()); complete(); }); Future<String> failed = Future.failedFuture(new RuntimeException("Woops")); failed.toCompletionStage() .whenComplete((str, err) -> { assertNull(str); assertTrue(err instanceof RuntimeException); assertEquals("Woops", err.getMessage()); assertSame(mainThread, Thread.currentThread()); complete(); }); await(); }
Source:
<code>public Date getExpiresOn() { <START> return new Date(mExpiresOn.getTime()); <END> }</code><technical_language>new Date(mExpiresOn.getTime()) [](start = 15, length = 30) returning a new object? #Closed</technical_language>

Target:
public Date getExpiresOn() { return Utility.getImmutableDateObject(mExpiresOn); }
Source:
<code><START> public Map<String, String> getTemplateVars() { <END> return templateVars; }</code><technical_language>I this return ImmutableMap emphasize immutability</technical_language>

Target:
public ImmutableMap<String, String> getTemplateVars() { return templateVars; }
Source:
<code>private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; <START> <END> synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { while (!mDevices.isEmpty()) { Device device = mDevices.remove(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } }</code><technical_language>extra tab white space in this empty line</technical_language>

Target:
private void handleExpectioninMonitorLoop(Exception e) { if (mQuit == false) { if (e instanceof TimeoutException) { Log.e("DeviceMonitor", "Adb connection Error: timeout"); } else { Log.e("DeviceMonitor", "Adb connection Error:" + e.getMessage()); } mMonitoring = false; if (mMainAdbConnection != null) { try { mMainAdbConnection.close(); } catch (IOException ioe) { } mMainAdbConnection = null; synchronized (AndroidDebugBridge.getLock()) { synchronized (mDevices) { for (int n = mDevices.size() -1; n >= 0; n--) { Device device = mDevices.get(0); removeDevice(device); mServer.deviceDisconnected(device); } } } } } }
Source:
<code>protected boolean parseArgs(final String[] argv) { commandLineParser = getCommandLineParser(); boolean ret = false; try { ret = commandLineParser.parseArguments(System.err, argv); } catch (CommandLineException e) { <START> System.err.println(e.getMessage()); <END> System.err.println(commandLineParser.usage(false,false)); ret = false; } commandLine = commandLineParser.getCommandLine(); if (!ret) { return false; } REFERENCE_SEQUENCE = referenceSequence.getReferenceFile(); final String[] customErrorMessages = customCommandLineValidation(); if (customErrorMessages != null) { for (final String msg : customErrorMessages) { System.err.println(msg); } System.err.print(commandLineParser.usage(false, false)); return false; } return true; }</code><technical_language>please reversing lines</technical_language>

Target:
protected boolean parseArgs(final String[] argv) { commandLineParser = getCommandLineParser(); boolean ret; try { ret = commandLineParser.parseArguments(System.err, argv); } catch (CommandLineException e) { System.err.println(commandLineParser.usage(false,false)); System.err.println(e.getMessage()); ret = false; } commandLine = commandLineParser.getCommandLine(); if (!ret) { return false; } REFERENCE_SEQUENCE = referenceSequence.getReferenceFile(); final String[] customErrorMessages = customCommandLineValidation(); if (customErrorMessages != null) { System.err.print(commandLineParser.usage(false, false)); for (final String msg : customErrorMessages) { System.err.println(msg); } return false; } return true; }
Source:
<code><START> private void writeMetadata(File parent, String resourceFileName, Properties metadata) throws SynapseException { <END> File metadataDir = new File(parent, METADATA_DIR_NAME); if (!metadataDir.exists() && !metadataDir.mkdirs()) { handleException("Unable to create metadata directory: " + metadataDir.getPath()); } File newMetadataFile = new File(metadataDir, resourceFileName + METADATA_FILE_SUFFIX); try (BufferedWriter metadataWriter = new BufferedWriter(new FileWriter(newMetadataFile))) { metadata.store(metadataWriter, null); if (log.isDebugEnabled()) { log.debug("Successfully written metadata to file: " + newMetadataFile.getPath()); } } catch (IOException e) { handleException("Couldn't write to metadata file: " + newMetadataFile.getPath(), e); } }</code><technical_language>some duplicate code in this method writeToFile method. refactor</technical_language>

Target:
private void writeMetadata(File parent, String resourceFileName, Properties metadata) { File metadataDir = new File(parent, METADATA_DIR_NAME); if (!metadataDir.exists() && !metadataDir.mkdirs()) { handleException("Unable to create metadata directory: " + metadataDir.getPath()); } File newMetadataFile = new File(metadataDir, resourceFileName + METADATA_FILE_SUFFIX); try (BufferedWriter metadataWriter = new BufferedWriter(new FileWriter(newMetadataFile))) { metadata.store(metadataWriter, null); if (log.isDebugEnabled()) { log.debug("Successfully written metadata to file: " + newMetadataFile.getPath()); } } catch (IOException e) { handleException("Couldn't write to metadata file: " + newMetadataFile.getPath(), e); } }
Source:
<code>public void trace(String component, String operation, Runnable runable) throws RuntimeException { try { startNewSpan(component, operation); runable.run(); } catch (Exception e) { <START> throw new RuntimeException(e.getMessage(), e); <END> } finally { finishSpan(); } }</code><technical_language>iirc Runnable declared exceptions, this wrap runtime exceptions in another runtime exception</technical_language>

Target:
public void trace(String component, String operation, Runnable runable) { try { startNewSpan(component, operation); runable.run(); } finally { finishSpan(); } }
Source:
<code>public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; <START> for (EntityRef minion : entityManager.getEntitiesWith(BehaviorComponent.class)) { <END> addEntity(minion, minion.getComponent(BehaviorComponent.class)); } for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }</code><technical_language>I suspect lifecycle events (OnAddedComponent), scanning entities BehaviourComponents frame</technical_language>

Target:
public void update(float delta) { if (speed > 0) { speed -= delta; return; } speed = 0.1f; for (Map.Entry<BehaviorTree, List<Interpreter>> entry : interpreters.entrySet()) { for (Interpreter interpreter : entry.getValue()) { interpreter.tick(0.1f); } } }
Source:
<code>public void run(DiscovererConfiguration configuration, Environment environment) { MongoClient mongoClient = new MongoClient(configuration.getDatabaseURL(), configuration.getDatabasePort()); Discoverer discoverer = new Discoverer(mongoClient, configuration.getActiveCrawlers()); environment.jersey().register(new FetchAPI(discoverer)); environment.jersey().register(new FetchAllAPI(discoverer)); environment.jersey().register(new DeleteAPI(discoverer)); environment.jersey().register(new StatisticsAPI(discoverer)); environment.jersey().register(new RefreshAPI(discoverer)); <START> environment.jersey().register(new FetchIfAPI(discoverer)); <END> }</code><technical_language>advantage of *API ? collapsed DiscovererApi maybe</technical_language>

Target:
public void run(DiscovererConfiguration configuration, Environment environment) { MongoClient mongoClient = new MongoClient(configuration.getDatabaseURL(), configuration.getDatabasePort()); Discoverer discoverer = new Discoverer(mongoClient, configuration.getActiveCrawlers()); environment.jersey().register(new DiscovererAPI(discoverer)); }
Source:
<code>default V setDataSource( CallbackDataProvider.FetchCallback<T, Void> fetchCallback) { setDataSource(DataProvider.fromCallbacks(fetchCallback, query -> { throw new IllegalStateException( "Trying to use defined size with a lazy loading component" + " without either providing a count callback for the" <START> + "component to fetch the size of the data or a data" <END> + "provider that implements the size query. Provide the " + "callback for fetching size with%n" + "component.getLazyDataView().withDefinedSize(CallbackDataProvider.CountCallback);" + "%nor switch to undefined size with%n" + "component.getLazyDataView().withUndefinedSize();"); })); V lazyDataView = getLazyDataView(); lazyDataView.setRowCountUnknown(); return lazyDataView; }</code><technical_language>suggestion + " component fetch size of data a data"</technical_language>

Target:
default V setDataSource( CallbackDataProvider.FetchCallback<T, Void> fetchCallback) { setDataSource(DataProvider.fromCallbacks(fetchCallback, query -> { throw new IllegalStateException( "Trying to use exact size with a lazy loading component" + " without either providing a count callback for the" + " component to fetch the size of the data or a data" + " provider that implements the size query. Provide the " + "callback for fetching size with%n" + "component.getLazyDataView().withDefinedSize(CallbackDataProvider.CountCallback);" + "%nor switch to undefined size with%n" + "component.getLazyDataView().withUndefinedSize();"); })); V lazyDataView = getLazyDataView(); lazyDataView.setRowCountUnknown(); return lazyDataView; }
Source:
<code>void testBuiltInListsIncludeAllBuiltInAbbreviations() { viewModel.addBuiltInList(); assertEquals(1, viewModel.journalFilesProperty().getSize()); viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0)); ObservableList<Abbreviation> expected = FXCollections.observableArrayList(repo.getBuiltin()); ObservableList<Abbreviation> actualAbbreviations = FXCollections <START> .observableArrayList(viewModel.abbreviationsProperty().stream() <END> .map(AbbreviationViewModel::getAbbreviationObject).collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); }</code><technical_language>Reformat necessary</technical_language>

Target:
void testBuiltInListsIncludeAllBuiltInAbbreviations() { viewModel.addBuiltInList(); assertEquals(1, viewModel.journalFilesProperty().getSize()); viewModel.currentFileProperty().set(viewModel.journalFilesProperty().get(0)); ObservableList<Abbreviation> expected = FXCollections.observableArrayList(repository.getAllLoaded()); ObservableList<Abbreviation> actualAbbreviations = FXCollections .observableArrayList(viewModel.abbreviationsProperty().stream() .map(AbbreviationViewModel::getAbbreviationObject) .collect(Collectors.toList())); assertEquals(expected, actualAbbreviations); }