auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void testInvalidNullDefaultForPotentiallyNonNullableArray() throws Exception { MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"field1\", \"type\": \"[]int32\", \"versions\": \"0+\", \"nullableVersions\": \"1+\", ", " \"default\": \"null\" }", " ]", "}")), MessageSpec.class); try { <START> new MessageDataGenerator("test").generate(testMessageSpec); <END> fail("Expected MessageDataGenerator#generate to fail"); } catch (RuntimeException e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("not all versions of this field are nullable")); } }</code><technical_language>This org.apache.kafka.common.message match directory generated source files outputted</technical_language>

Target:
public void testInvalidNullDefaultForPotentiallyNonNullableArray() throws Exception { MessageSpec testMessageSpec = MessageGenerator.JSON_SERDE.readValue(String.join("", Arrays.asList( "{", " \"type\": \"request\",", " \"name\": \"FooBar\",", " \"validVersions\": \"0-2\",", " \"fields\": [", " { \"name\": \"field1\", \"type\": \"[]int32\", \"versions\": \"0+\", \"nullableVersions\": \"1+\", ", " \"default\": \"null\" }", " ]", "}")), MessageSpec.class); try { new MessageDataGenerator("org.apache.kafka.common.message").generate(testMessageSpec); fail("Expected MessageDataGenerator#generate to fail"); } catch (RuntimeException e) { assertTrue("Invalid error message: " + e.getMessage(), e.getMessage().contains("not all versions of this field are nullable")); } }
Source:
<code>private ZkBaseDataAccessor(RealmAwareZkClient zkClient, boolean usesExternalZkClient) { if (zkClient == null) { <START> throw new NullPointerException("zkclient is null"); <END> } _zkClient = zkClient; _usesExternalZkClient = usesExternalZkClient; }</code><technical_language>minor: throw out IllegalArgumentException instead</technical_language>

Target:
private ZkBaseDataAccessor(RealmAwareZkClient zkClient, boolean usesExternalZkClient) { if (zkClient == null) { throw new IllegalArgumentException("zkclient is null"); } _zkClient = zkClient; _usesExternalZkClient = usesExternalZkClient; }
Source:
<code>protected void onHandleIntent(Intent intent) { Log.i(TAG, "Handle Intent"); broadcastManager.sendBroadcast(runningBroadcast()); final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE); Log.i(TAG, "Type: " + type); try { switch (type) { case DOWNLOAD_TRAINING: searchTraining(intent.getStringExtra(MINISTRY_ID), intent.getStringExtra(MINISTRY_MCC)); break; case SYNC_TRAINING: syncTraining(intent); break; case SYNC_DIRTY_TRAINING: <START> syncDirtyTraining(); <END> default: break; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } }</code><technical_language>break;</technical_language>

Target:
protected void onHandleIntent(Intent intent) { Log.i(TAG, "Handle Intent"); broadcastManager.sendBroadcast(runningBroadcast()); final Type type = (Type) intent.getSerializableExtra(EXTRA_TYPE); Log.i(TAG, "Type: " + type); try { switch (type) { case DOWNLOAD_TRAINING: searchTraining(intent.getStringExtra(MINISTRY_ID), intent.getStringExtra(MINISTRY_MCC)); break; case SYNC_TRAINING: syncTraining(intent); break; case SYNC_DIRTY_TRAINING: syncDirtyTraining(); break; default: break; } } catch (Exception e) { Log.e(TAG, e.getMessage(), e); } }
Source:
<code>protected void execute() { <START> logger.debug("execute() method is called!"); <END> try { final InfoResponse response = createProtocol().info(); for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); State result = null; switch (provider.getNeoStatProperty(itemName)) { case CurrentTemperature: result = new DecimalType(response.getDevice(device) .getCurrentTemperature()); break; case CurrentFloorTemperature: result = new DecimalType(response.getDevice(device) .getCurrentFloorTemperature()); break; case CurrentSetTemperature: result = new DecimalType(response.getDevice(device) .getCurrentSetTemperature()); break; case DeviceName: result = new StringType(response.getDevice(device) .getDeviceName()); break; case Away: result = response.getDevice(device).isAway() ? OnOffType.ON : OnOffType.OFF; break; case Standby: result = response.getDevice(device).isStandby() ? OnOffType.ON : OnOffType.OFF; break; case Heating: result = response.getDevice(device).isHeating() ? OnOffType.ON : OnOffType.OFF; break; } if (eventPublisher != null && result != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.error( "Failed to parse response or fetch expected result from it. Please check your configuration.", e); return; } }</code><technical_language>please decrease log level trace remove statement</technical_language>

Target:
protected void execute() { try { final InfoResponse response = createProtocol().info(); for (NeoHubBindingProvider provider : providers) { for (String itemName : provider.getItemNames()) { final String device = provider.getNeoStatDevice(itemName); final NeoStatProperty property = provider .getNeoStatProperty(itemName); final State result = mapResponseToState(response, device, property); if (eventPublisher != null) { eventPublisher.postUpdate(itemName, result); } } } } catch (final RuntimeException e) { logger.warn("Failed to fetch info from neo hub.", e); } }
Source:
<code>private void doPoll() { log.debug("Starting polling of segment table"); final List<DataSegment> segments = connector.inReadOnlyTransaction( new TransactionCallback<List<DataSegment>>() { @Override public List<DataSegment> inTransaction(Handle handle, TransactionStatus status) { return handle .createQuery(StringUtils.format("SELECT payload FROM %s WHERE used=true", getSegmentsTable())) .setFetchSize(connector.getStreamingFetchSize()) .map( new ResultSetMapper<DataSegment>() { @Override public DataSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { DataSegment segment = jsonMapper.readValue(r.getBytes("payload"), DataSegment.class); return replaceWithExistingSegmentIfPresent(segment); } catch (IOException e) { log.makeAlert(e, "Failed to read segment from db.").emit(); return null; } } } ) .list(); } } ); ImmutableMap<String, String> dataSourceProperties = createDefaultDataSourceProperties(); if (segments == null || segments.isEmpty()) { log.info("No segments found in the database!"); <START> dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments(Collections.emptyList(), dataSourceProperties); <END> } else { log.info("Polled and found %,d segments in the database", segments.size()); dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments( Iterables.filter(segments, Objects::nonNull), dataSourceProperties ); } }</code><technical_language>I segments == null is here, if dataSourcesSnapshot is non-null, this assignment skipped. intermittent database unavailability failure. This condition logged</technical_language>

Target:
private void doPoll() { log.debug("Starting polling of segment table"); final List<DataSegment> segments = connector.inReadOnlyTransaction( new TransactionCallback<List<DataSegment>>() { @Override public List<DataSegment> inTransaction(Handle handle, TransactionStatus status) { return handle .createQuery(StringUtils.format("SELECT payload FROM %s WHERE used=true", getSegmentsTable())) .setFetchSize(connector.getStreamingFetchSize()) .map( new ResultSetMapper<DataSegment>() { @Override public DataSegment map(int index, ResultSet r, StatementContext ctx) throws SQLException { try { DataSegment segment = jsonMapper.readValue(r.getBytes("payload"), DataSegment.class); return replaceWithExistingSegmentIfPresent(segment); } catch (IOException e) { log.makeAlert(e, "Failed to read segment from db.").emit(); return null; } } } ) .list(); } } ); Preconditions.checkNotNull( segments, "Unexpected 'null' when polling segments from the db, aborting snapshot update." ); ImmutableMap<String, String> dataSourceProperties = createDefaultDataSourceProperties(); if (segments.isEmpty()) { log.info("No segments found in the database!"); } else { log.info("Polled and found %,d segments in the database", segments.size()); } dataSourcesSnapshot = DataSourcesSnapshot.fromUsedSegments( Iterables.filter(segments, Objects::nonNull), dataSourceProperties ); }
Source:
<code>public <B extends BlockStateHolder<B>> void sendFakeBlock(BlockVector3 pos, B block) { World world = getWorld(); if (!(world instanceof ForgeWorld)) { return; } BlockPos loc = ForgeAdapter.toBlockPos(pos); if (block == null) { final SChangeBlockPacket packetOut = new SChangeBlockPacket(((ForgeWorld) world).getWorld(), loc); player.connection.sendPacket(packetOut); } else { final SChangeBlockPacket packetOut = new SChangeBlockPacket(); PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); buf.writeBlockPos(loc); buf.writeVarInt(Block.getStateId(ForgeAdapter.adapt(block.toImmutableState()))); try { packetOut.readPacketData(buf); } catch (IOException e) { return; } player.connection.sendPacket(packetOut); if (block instanceof BaseBlock) { final BaseBlock baseBlock = (BaseBlock) block; final CompoundTag nbtData = baseBlock.getNbtData(); if (nbtData != null) { player.connection.sendPacket(new SUpdateTileEntityPacket( <START> new BlockPos(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()), 7, <END> NBTConverter.toNative(nbtData)) ); } } } }</code><technical_language>put 7 in a constant field, named STRUCTURE_BLOCK_TILE_ENTITY_ID something? Honestly, careful this, 7 work if start non-structure blocks. a map of IDs</technical_language>

Target:
public <B extends BlockStateHolder<B>> void sendFakeBlock(BlockVector3 pos, B block) { World world = getWorld(); if (!(world instanceof ForgeWorld)) { return; } BlockPos loc = ForgeAdapter.toBlockPos(pos); if (block == null) { final SChangeBlockPacket packetOut = new SChangeBlockPacket(((ForgeWorld) world).getWorld(), loc); player.connection.sendPacket(packetOut); } else { final SChangeBlockPacket packetOut = new SChangeBlockPacket(); PacketBuffer buf = new PacketBuffer(Unpooled.buffer()); buf.writeBlockPos(loc); buf.writeVarInt(Block.getStateId(ForgeAdapter.adapt(block.toImmutableState()))); try { packetOut.readPacketData(buf); } catch (IOException e) { return; } player.connection.sendPacket(packetOut); if (block instanceof BaseBlock && block.getBlockType().equals(BlockTypes.STRUCTURE_BLOCK)) { final BaseBlock baseBlock = (BaseBlock) block; final CompoundTag nbtData = baseBlock.getNbtData(); if (nbtData != null) { player.connection.sendPacket(new SUpdateTileEntityPacket( new BlockPos(pos.getBlockX(), pos.getBlockY(), pos.getBlockZ()), STRUCTURE_BLOCK_PACKET_ID, NBTConverter.toNative(nbtData)) ); } } } }
Source:
<code>public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( EnableModule.class.getName(), false); List<String> registeredChannelNames = new ArrayList<>(); for (Class<?> type : collectClasses(attributes.get("value"))) { registeredChannelNames.addAll(MessageChannelBeanDefinitionRegistryUtils.registerChannelBeanDefinitions(type, registry)); MessageChannelBeanDefinitionRegistryUtils.registerChannelsQualifiedBeanDefinitions( ClassUtils.resolveClassName(metadata.getClassName(), null), type, registry); } Properties defaultChannelNameProperties = new Properties(); for (String registeredChannelName : registeredChannelNames) { defaultChannelNameProperties.put(SPRING_CLOUD_STREAM_BINDINGS_PREFIX + "." + registeredChannelName, <START> "${spring.application.name:spring.cloud.stream}" + "." + registeredChannelName); <END> } if (environment != null) { environment.getPropertySources().addLast( new PropertiesPropertySource("default-spring-cloud-stream-channel-bindings", defaultChannelNameProperties)); } }</code><technical_language>default binding names registered, remove default name handling ChannelBindingProperties's getBindingPath(String channelName)</technical_language>

Target:
public void registerBeanDefinitions(AnnotationMetadata metadata, BeanDefinitionRegistry registry) { MultiValueMap<String, Object> attributes = metadata.getAllAnnotationAttributes( EnableModule.class.getName(), false); List<String> registeredChannelNames = new ArrayList<>(); for (Class<?> type : collectClasses(attributes.get("value"))) { registeredChannelNames.addAll(MessageChannelBeanDefinitionRegistryUtils.registerChannelBeanDefinitions(type, registry)); MessageChannelBeanDefinitionRegistryUtils.registerChannelsQualifiedBeanDefinitions( ClassUtils.resolveClassName(metadata.getClassName(), null), type, registry); } Properties defaultChannelNameProperties = new Properties(); for (String registeredChannelName : registeredChannelNames) { defaultChannelNameProperties.put(SPRING_CLOUD_STREAM_BINDINGS_PREFIX + "." + registeredChannelName, "${spring.application.name:spring.cloud.stream}" + "." + registeredChannelName); } environment.getPropertySources().addLast( new PropertiesPropertySource("default-spring-cloud-stream-channel-bindings", defaultChannelNameProperties)); }
Source:
<code>protected void onStart() { super.onStart(); if (searchQuery != null) { setTitle(getString(R.string.discussion_posts_search_title)); return; } if (discussionTopic != null && discussionTopic.getName() != null) { if (discussionTopic.getIdentifier().equals(DiscussionTopic.FOLLOWING_TOPICS_ID)) { SpannableString title = new SpannableString(" " + discussionTopic.getName()); Drawable starIcon = new IconDrawable(this, FontAwesomeIcons.fa_star) .colorRes(this, R.color.edx_grayscale_neutral_white_t) .sizeRes(this, R.dimen.edx_base); <START> starIcon.setBounds(0, 0, starIcon.getIntrinsicWidth(), starIcon.getIntrinsicHeight()); <END> ImageSpan iSpan = new ImageSpan(starIcon, ImageSpan.ALIGN_BASELINE); title.setSpan(iSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); setTitle(title); } else { setTitle(discussionTopic.getName()); } } }</code><technical_language>Unsure is a tint set, setting tint null remove tint. starIcon.setTintList(null);</technical_language>

Target:
protected void onStart() { super.onStart(); if (searchQuery != null) { setTitle(getString(R.string.discussion_posts_search_title)); return; } if (discussionTopic != null && discussionTopic.getName() != null) { if (discussionTopic.getIdentifier().equals(DiscussionTopic.FOLLOWING_TOPICS_ID)) { SpannableString title = new SpannableString(" " + discussionTopic.getName()); IconDrawable starIcon = new IconDrawable(this, FontAwesomeIcons.fa_star) .colorRes(this, R.color.edx_grayscale_neutral_white_t) .sizeRes(this, R.dimen.edx_base); starIcon.setBounds(0, 0, starIcon.getIntrinsicWidth(), starIcon.getIntrinsicHeight()); starIcon.setTintList(null); ImageSpan iSpan = new ImageSpan(starIcon, ImageSpan.ALIGN_BASELINE); title.setSpan(iSpan, 0, 1, Spanned.SPAN_INCLUSIVE_EXCLUSIVE); setTitle(title); } else { setTitle(discussionTopic.getName()); } } }
Source:
<code>public UnaliasSymbolReferences(FunctionManager functionManager) { <START> this.functionManager = functionManager; <END> }</code><technical_language>requireNonNull</technical_language>

Target:
public UnaliasSymbolReferences(FunctionManager functionManager) { this.functionManager = requireNonNull(functionManager, "functionManager is null"); }
Source:
<code>protected void prepareBuffer() { bufferToSend = PooledByteBufAllocator.DEFAULT.ioBuffer( (int) super.sizeInBytes() + (Partition_Response_Info_List_Size + partitionResponseInfoSize)); writeHeader(); if (partitionResponseInfoList != null) { bufferToSend.writeInt(partitionResponseInfoList.size()); for (PartitionResponseInfo partitionResponseInfo : partitionResponseInfoList) { partitionResponseInfo.writeTo(bufferToSend); } } if (toSend != null) { if (toSend.content() != null) { int maxNumComponent = 1 + toSend.content().nioBufferCount(); CompositeByteBuf compositeByteBuf = bufferToSend.alloc().compositeHeapBuffer(maxNumComponent); compositeByteBuf.addComponent(true, bufferToSend); compositeByteBuf.addFlattenedComponents(true, toSend.content()); <START> bufferToSend = compositeByteBuf; <END> toSend = null; } } }</code><technical_language>create a test verify content of GetResponse</technical_language>

Target:
protected void prepareBuffer() { bufferToSend = PooledByteBufAllocator.DEFAULT.ioBuffer( (int) super.sizeInBytes() + (Partition_Response_Info_List_Size + partitionResponseInfoSize)); writeHeader(); if (partitionResponseInfoList != null) { bufferToSend.writeInt(partitionResponseInfoList.size()); for (PartitionResponseInfo partitionResponseInfo : partitionResponseInfoList) { partitionResponseInfo.writeTo(bufferToSend); } } if (toSend != null) { ByteBuf toSendContent = toSend.content(); if (toSendContent != null) { int maxNumComponent = 1 + toSendContent.nioBufferCount(); CompositeByteBuf compositeByteBuf = bufferToSend.alloc().compositeDirectBuffer(maxNumComponent); compositeByteBuf.addComponent(true, bufferToSend); if (toSendContent instanceof CompositeByteBuf) { Iterator<ByteBuf> iterator = ((CompositeByteBuf) toSendContent).iterator(); while (iterator.hasNext()) { compositeByteBuf.addComponent(true, iterator.next()); } } else { compositeByteBuf.addComponent(true, toSendContent); } bufferToSend = compositeByteBuf; sendSizeInBufferToSend = toSendContent.readableBytes(); toSend = null; } } }
Source:
<code>@Override public void setCard(@NonNull AnnouncementCard card) { super.setCard(card); if (!TextUtils.isEmpty(card.extract())) { textView.setText(StringUtil.fromHtml(card.extract())); } if (!card.hasAction()) { actionViewPositive.setVisibility(GONE); actionViewNegative.setVisibility(GONE); } else { actionViewPositive.setVisibility(VISIBLE); actionViewNegative.setVisibility(VISIBLE); actionViewPositive.setText(card.actionTitle()); } if (!TextUtils.isEmpty(card.negativeText())) { actionViewNegative.setText(card.negativeText()); } else { actionViewNegative.setVisibility(GONE); } if (card.hasImage()) { headerImageView.setVisibility(VISIBLE); headerImageView.loadImage(card.image()); } else { headerImageView.setVisibility(GONE); } if (card.imageHeight() > 0) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) headerImageView.getLayoutParams(); params.height = DimenUtil.roundedDpToPx(card.imageHeight()); headerImageView.setLayoutParams(params); } if (card.hasFooterCaption()) { footerTextView.setText(StringUtil.fromHtml(card.footerCaption())); <START> RichTextUtil.removeUnderlinesFromLinks(footerTextView); <END> } else { footerTextView.setVisibility(GONE); footerBorderView.setVisibility(GONE); } if (card.hasBorder()) { } }</code><technical_language>@cooltey Line #93 border condition needs care of. thick red borders previously. need some solution now</technical_language>

Target:
@Override public void setCard(@NonNull AnnouncementCard card) { super.setCard(card); if (!TextUtils.isEmpty(card.extract())) { textView.setText(StringUtil.fromHtml(card.extract())); } if (!card.hasAction()) { actionViewPositive.setVisibility(GONE); actionViewNegative.setVisibility(GONE); } else { actionViewPositive.setVisibility(VISIBLE); actionViewNegative.setVisibility(VISIBLE); actionViewPositive.setText(card.actionTitle()); } if (!TextUtils.isEmpty(card.negativeText())) { actionViewNegative.setText(card.negativeText()); } else { actionViewNegative.setVisibility(GONE); } if (card.hasImage()) { headerImageView.setVisibility(VISIBLE); headerImageView.loadImage(card.image()); } else { headerImageView.setVisibility(GONE); } if (card.imageHeight() > 0) { ViewGroup.MarginLayoutParams params = (ViewGroup.MarginLayoutParams) headerImageView.getLayoutParams(); params.height = DimenUtil.roundedDpToPx(card.imageHeight()); headerImageView.setLayoutParams(params); } if (card.hasFooterCaption()) { footerTextView.setText(StringUtil.fromHtml(card.footerCaption())); RichTextUtil.removeUnderlinesFromLinks(footerTextView); } else { footerTextView.setVisibility(GONE); footerBorderView.setVisibility(GONE); } if (card.hasBorder()) { container.setStrokeColor(getResources().getColor(R.color.red30)); container.setStrokeWidth(10); } else { container.setDefaultBorder(); } }
Source:
<code>private String getFirstRevision(String fullpath) throws IOException { String[] argv = { ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK), "rev-list", "--reverse", <START> "HEAD", <END> "--", fullpath }; Executor executor = new Executor(Arrays.asList(argv), new File(getDirectoryName()), RuntimeEnvironment.getInstance().getInteractiveCommandTimeout()); int status = executor.exec(); try (BufferedReader in = new BufferedReader( new InputStreamReader(executor.getOutputStream()))) { String line; if ((line = in.readLine()) != null) { return line.trim(); } } if (status != 0) { LOGGER.log(Level.WARNING, "Failed to get first revision for: \"{0}\" Exit code: {1}", new Object[]{fullpath, String.valueOf(status)}); return null; } return null; }</code><technical_language>big problem some food for thought: * Executor.exec() Executor.exec(boolean) spool entire output of a program memory. a burdensome amount this removal of --max-count, this is a rev-list of a single file. * spooled bytes read line 402, read default Java charset, is locale dependent OS installation. For hashes of a rev-list, is OK - remarking in GitRepository, specific effort is a correct charset (see newLogReader()). * Technically read line 402, a BufferedReader is overkill, bytes fully spooled in-memory. * output of a Process (via exec()) read else a deadlock happen awaits process exit value. default spool consume everything. I if this is opportunity create a HeadHandler implementation of Executor.StreamHandler is line-oriented (e.g. characters out of bytes), demands a encoding instead of allowing default Java charset, reads stores a maximum number of lines consumes discards bytes (without bothering character conversion) exhaust stream avoid allocating heap</technical_language>

Target:
private String getFirstRevision(String fullpath) throws IOException { String[] argv = { ensureCommand(CMD_PROPERTY_KEY, CMD_FALLBACK), "rev-list", "--reverse", "HEAD", "--", fullpath }; Executor executor = new Executor(Arrays.asList(argv), new File(getDirectoryName()), RuntimeEnvironment.getInstance().getInteractiveCommandTimeout()); HeadHandler headHandler = new HeadHandler(1); int status = executor.exec(false, headHandler); String line; if (headHandler.count() > 0 && (line = headHandler.get(0)) != null) { return line.trim(); } LOGGER.log(Level.WARNING, "Failed to get first revision for: \"{0}\" Exit code: {1}", new Object[]{fullpath, String.valueOf(status)}); return null; }
Source:
<code>protected CoordinatorStreamSystemConsumer initializeCoordinatorStreamConsumer(JobInstance jobInstance) { CoordinatorStreamSystemFactory coordinatorStreamSystemFactory = new CoordinatorStreamSystemFactory(); Config coordinatorSystemConfig = getCoordinatorSystemConfig(jobInstance); <START> LOG.info("Using config: to create coordinatorStream consumer.", coordinatorSystemConfig); <END> CoordinatorStreamSystemConsumer consumer = coordinatorStreamSystemFactory.getCoordinatorStreamSystemConsumer(coordinatorSystemConfig, METRICS_REGISTRY); LOG.info("Registering coordinator system stream consumer."); consumer.register(); LOG.debug("Starting coordinator system stream consumer."); consumer.start(); LOG.debug("Bootstrapping coordinator system stream consumer."); consumer.bootstrap(); return consumer; }</code><technical_language>This is happen time getTasks is called. INFO level spamy</technical_language>

Target:
protected CoordinatorStreamSystemConsumer initializeCoordinatorStreamConsumer(JobInstance jobInstance) { CoordinatorStreamSystemFactory coordinatorStreamSystemFactory = new CoordinatorStreamSystemFactory(); Config coordinatorSystemConfig = getCoordinatorSystemConfig(jobInstance); LOG.debug("Using config: to create coordinatorStream consumer.", coordinatorSystemConfig); CoordinatorStreamSystemConsumer consumer = coordinatorStreamSystemFactory.getCoordinatorStreamSystemConsumer(coordinatorSystemConfig, METRICS_REGISTRY); LOG.debug("Registering coordinator system stream consumer."); consumer.register(); LOG.debug("Starting coordinator system stream consumer."); consumer.start(); LOG.debug("Bootstrapping coordinator system stream consumer."); consumer.bootstrap(); return consumer; }
Source:
<code>public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); <START> get(DyeableData.class) <END> .ifPresent( manipulators::add); }</code><technical_language>faster methods, data processors possible</technical_language>

Target:
public void supplyVanillaManipulators(List<DataManipulator<?, ?>> manipulators) { super.supplyVanillaManipulators(manipulators); if (this.color != null) { manipulators.add(new SpongeDyeableData((DyeColor) (Object) this.color)); } }
Source:
<code>private List<String> listFiles(String prefix, File[] files) { File dir = worldEdit.getWorkingDirectoryFile(prefix); if (prefix == null) prefix = ""; List<String> result = new ArrayList<String>(); for (File file : files) { StringBuilder build = new StringBuilder(); build.append("\u00a72"); ClipboardFormat format = ClipboardFormat.findByFile(file); boolean inRoot = file.getParentFile().getName().equals(prefix); if (inRoot) { build.append(file.getName()); } else { String relative = dir.toURI().relativize(file.toURI()).getPath(); <START> String[] split = file.getPath().split(Pattern.quote(prefix + File.separator)); <END> build.append(relative); } build.append(": ").append(format == null ? "Unknown" : format.name()); result.add(build.toString()); } return result; }</code><technical_language>this variable</technical_language>

Target:
private List<String> listFiles(String prefix, File[] files) { File dir = worldEdit.getWorkingDirectoryFile(prefix); if (prefix == null) prefix = ""; List<String> result = new ArrayList<String>(); for (File file : files) { StringBuilder build = new StringBuilder(); build.append("\u00a72"); ClipboardFormat format = ClipboardFormat.findByFile(file); boolean inRoot = file.getParentFile().getName().equals(prefix); if (inRoot) { build.append(file.getName()); } else { String relative = dir.toURI().relativize(file.toURI()).getPath(); build.append(relative); } build.append(": ").append(format == null ? "Unknown" : format.name()); result.add(build.toString()); } return result; }
Source:
<code>public long srem(Collection<ByteArrayWrapper> membersToRemove) { AtomicLong removedCount = new AtomicLong(); region().computeIfPresent(key, (_unusedKey_, oldValue) -> { Set<ByteArrayWrapper> newValue = createSet(oldValue); newValue.removeAll(membersToRemove); removedCount.set(oldValue.size() - newValue.size()); return newValue; }); if (members().isEmpty()) { <START> RedisDataType type = context.getKeyRegistrar().getType(key); <END> context.getRegionProvider().removeKey(key, type); } return removedCount.longValue(); }</code><technical_language>wrong refetch RedisDataType blow checking if type is expect. For example check if is == REDIS_SET calling removeKey</technical_language>

Target:
public long srem(Collection<ByteArrayWrapper> membersToRemove) { AtomicLong removedCount = new AtomicLong(); region().computeIfPresent(key, (_unusedKey_, oldValue) -> { Set<ByteArrayWrapper> newValue = createSet(oldValue); newValue.removeAll(membersToRemove); removedCount.set(oldValue.size() - newValue.size()); return newValue; }); if (members().isEmpty()) { RedisDataType type = context.getKeyRegistrar().getType(key); if (type == RedisDataType.REDIS_SET) { context.getRegionProvider().removeKey(key, type); } } return removedCount.longValue(); }
Source:
<code>public static void printMetrics(Nimbus.Iface client, String name) throws Exception { TopologySummary ts = client.getTopologySummaryByName(name); <START> if (ts == null) { <END> throw new Exception("Could not find a topology named " + name); } String id = ts.get_id(); TopologyInfo info = client.getTopologyInfo(id); int uptime = info.get_uptime_secs(); long acked = 0; long failed = 0; double weightedAvgTotal = 0.0; for (ExecutorSummary exec : info.get_executors()) { if ("spout".equals(exec.get_component_id())) { SpoutStats stats = exec.get_stats().get_specific().get_spout(); Map<String, Long> failedMap = stats.get_failed().get(":all-time"); Map<String, Long> ackedMap = stats.get_acked().get(":all-time"); Map<String, Double> avgLatMap = stats.get_complete_ms_avg().get(":all-time"); for (String key : ackedMap.keySet()) { if (failedMap != null) { Long tmp = failedMap.get(key); if (tmp != null) { failed += tmp; } } long ackVal = ackedMap.get(key); double latVal = avgLatMap.get(key) * ackVal; acked += ackVal; weightedAvgTotal += latVal; } } } double avgLatency = weightedAvgTotal / acked; System.out.println("uptime: " + uptime + " acked: " + acked + " avgLatency: " + avgLatency + " acked/sec: " + (((double) acked) / uptime + " failed: " + failed)); }</code><technical_language>I beliefve this is longer needed, if getTopologySummaryByName fails, getTopologySummaryByName throw TException RuntimeException. If this is case, other places invoke getTopologySummaryByName deal result=null</technical_language>

Target:
public static void printMetrics(Nimbus.Iface client, String name) throws Exception { TopologyInfo info = client.getTopologyInfoByName(name); int uptime = info.get_uptime_secs(); long acked = 0; long failed = 0; double weightedAvgTotal = 0.0; for (ExecutorSummary exec : info.get_executors()) { if ("spout".equals(exec.get_component_id())) { SpoutStats stats = exec.get_stats().get_specific().get_spout(); Map<String, Long> failedMap = stats.get_failed().get(":all-time"); Map<String, Long> ackedMap = stats.get_acked().get(":all-time"); Map<String, Double> avgLatMap = stats.get_complete_ms_avg().get(":all-time"); for (String key : ackedMap.keySet()) { if (failedMap != null) { Long tmp = failedMap.get(key); if (tmp != null) { failed += tmp; } } long ackVal = ackedMap.get(key); double latVal = avgLatMap.get(key) * ackVal; acked += ackVal; weightedAvgTotal += latVal; } } } double avgLatency = weightedAvgTotal / acked; System.out.println("uptime: " + uptime + " acked: " + acked + " avgLatency: " + avgLatency + " acked/sec: " + (((double) acked) / uptime + " failed: " + failed)); }
Source:
<code>private static void failWithCorruptionException(boolean failOnCorruptedParquetStatistics, String column, ParquetDataSourceId id, Statistics statistics) { if (failOnCorruptedParquetStatistics) { <START> throw new ParquetCorruptionException(format("Corrupted statistics for column %s in Parquet file %s: %s", column, id, statistics)); <END> } }</code><technical_language>I hope children of Statistics type toString implemented</technical_language>

Target:
private static void failWithCorruptionException(boolean failOnCorruptedParquetStatistics, String column, ParquetDataSourceId id, Statistics statistics) throws ParquetCorruptionException { if (failOnCorruptedParquetStatistics) { throw new ParquetCorruptionException(format("Corrupted statistics for column \"%s\" in Parquet file \"%s\": [%s]", column, id, statistics)); } }
Source:
<code>public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } for (int index = 0; index < ids.size(); index++) { <START> dataMap.get(dataType).put(ids.get(index), values.get(index)); <END> } } finally { readWriteLock.writeLock().unlock(); } }</code><technical_language>move dataMap.get(dataType) out of for loop? extra hash computation for iteration. (It's JIT smartly remove a bit of overhead, sure.)</technical_language>

Target:
public <T> void putList(final String dataType, final List<Long> ids, final List<T> values) { if (ids.size() != values.size()) { throw new RuntimeException("Different list sizes: ids " + ids.size() + ", values " + values.size()); } readWriteLock.writeLock().lock(); try { if (!dataMap.containsKey(dataType)) { dataMap.put(dataType, new TreeMap<Long, Object>()); } final Map<Long, Object> innerMap = dataMap.get(dataType); for (int index = 0; index < ids.size(); index++) { innerMap.put(ids.get(index), values.get(index)); } } finally { readWriteLock.writeLock().unlock(); } }
Source:
<code>public static Version parseVersion(String text) { Version version = new Version(); String parts[] = text.split("\\.", -1); <START> <END> version.setFullVersion(text); version.setMajor(Integer.parseInt(parts[0])); version.setMinor(Integer.parseInt(parts[1])); if (parts[2].contains("-")) { version.setBuild(Integer.parseInt(parts[2].split("-")[0])); } else { version.setBuild(Integer.parseInt(parts[2])); } version.setRevision(Integer.parseInt(parts[3])); return version; }</code><technical_language>Please bring switch statement. This throw array index out of bounds exception</technical_language>

Target:
public static Version parseVersion(String text) { Version version = new Version(); String parts[] = text.split("\\.", -1); switch (parts.length) { case 4: version.setRevision(Integer.parseInt(parts[3])); case 3: version.setBuild(Integer.parseInt(parts[2])); case 2: version.setMinor(Integer.parseInt(parts[1])); case 1: version.setMajor(Integer.parseInt(parts[0])); } return version; }
Source:
<code>private NetworkFilter resolveVnicProfileDefaultNetworkFilter() { final Version dataCenterVersion = resolveDataCenterVersion(); <START> NetworkFilter networkFilter = null; <END> if (FeatureSupported.antiMacSpoofing(dataCenterVersion) && Config.<Boolean> getValue(ConfigValues.EnableMACAntiSpoofingFilterRules)) { networkFilter = networkFilterDao.getNetworkFilterByName(NetworkFilter.VDSM_NO_MAC_SPOOFING); } return networkFilter; }</code><technical_language>need for this variable in broad scope. If want define name for this value, define this variable of 'if'</technical_language>

Target:
private NetworkFilter resolveVnicProfileDefaultNetworkFilter() { if (Config.<Boolean> getValue(ConfigValues.EnableMACAntiSpoofingFilterRules)) { return networkFilterDao.getNetworkFilterByName(NetworkFilter.VDSM_NO_MAC_SPOOFING); } return null; }
Source:
<code>public Map<String, String> toMap() { <START> return ImmutableMap.of("account_id", accountId); <END> }</code><technical_language>I this stripe_account_id ? PP-4302</technical_language>

Target:
public Map<String, String> toMap() { return ImmutableMap.of("stripe_account_id", accountId); }
Source:
<code>public void providerMapped(RepositoryProvider provider) { Object[] allListeners = listeners.getListeners(); for (Object <START> allListener : <END> allListeners) { IRepositoryProviderListener listener = (IRepositoryProviderListener) allListener; listener.providerMapped(provider); } }</code><technical_language>listener ;) 'l' enough</technical_language>

Target:
public void providerMapped(RepositoryProvider provider) { Object[] allListeners = listeners.getListeners(); for (Object l : allListeners) { IRepositoryProviderListener listener = (IRepositoryProviderListener) l; listener.providerMapped(provider); } }
Source:
<code>public void testCache() { final ICache<Object, Object> cache = hz.getCacheManager().getCache(CACHE_NAME); Random random = new Random(); for (int i = 0; i < EVENT_COUNTER; i++) { int key = random.nextInt(Integer.MAX_VALUE); cache.putAsync(key, 23); cache.removeAsync(key); } <START> assertHasStatsEventually("/hz/" + CACHE_NAME, "cache."); <END> }</code><technical_language>minor: CacheUtil.getDistributedObjectName(CACHE_NAME) instead of string concatenation</technical_language>

Target:
public void testCache() { final ICache<Object, Object> cache = hz.getCacheManager().getCache(CACHE_NAME); Random random = new Random(); for (int i = 0; i < EVENT_COUNTER; i++) { int key = random.nextInt(Integer.MAX_VALUE); cache.putAsync(key, 23); cache.removeAsync(key); } assertHasStatsEventually(getDistributedObjectName(CACHE_NAME), "cache."); }
Source:
<code>public Authentication authenticate(Authentication authentication) throws AuthenticationException { BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication; Jwt jwt; try { jwt = this.jwtDecoder.decode(bearer.getToken()); } catch (JwtException failed) { OAuth2Error invalidToken = invalidToken(failed.getMessage()); throw new OAuth2AuthenticationException(invalidToken); } OAuth2TokenValidatorResult<OAuth2Error> result = this.jwtValidator.validate(jwt); if ( !result.isSuccess() ) { Collection<OAuth2Error> details = result.getDetails(); if ( details.size() == 1 ) { throw new OAuth2AuthenticationException(details.iterator().next()); } else { <START> throw new OAuth2DetailedAuthenticationException(details.iterator().next(), details); <END> } } JwtAuthenticationToken token = this.jwtConverter.convert(jwt); token.setDetails(bearer.getDetails()); return token; }</code><technical_language>OAuth2DetailedAuthenticationException is created anywhere? intention/purpose of this exception other aggregating errors</technical_language>

Target:
public Authentication authenticate(Authentication authentication) throws AuthenticationException { BearerTokenAuthenticationToken bearer = (BearerTokenAuthenticationToken) authentication; Jwt jwt; try { jwt = this.jwtDecoder.decode(bearer.getToken()); } catch (JwtException failed) { OAuth2Error invalidToken = invalidToken(failed.getMessage()); throw new OAuth2AuthenticationException(invalidToken, invalidToken.getDescription(), failed); } JwtAuthenticationToken token = this.jwtConverter.convert(jwt); token.setDetails(bearer.getDetails()); return token; }
Source:
<code>@Override public void process() throws IOException { try { HRegion region = (HRegion)this.rss.getRegion(this.regionInfo.getEncodedName()); if (region == null) { LOG.warn("Received CLOSE for but not ONLINE; ignoring CLOSE request", this.regionInfo.getRegionNameAsString()); return; } if (region.getCoprocessorHost() != null) { region.getCoprocessorHost().preClose(abort); } if (region.close(abort) == null) { LOG.warn("Can't close {}, already closed; split? (Unexpected state - investigate)", this.regionInfo.getRegionNameAsString()); return; } this.rss.removeRegion(region, destination); boolean b = reportRegionStateTransition(); LOG.debug("Closed (notified master={})", this.regionInfo.getRegionNameAsString(), b); } finally { <START> this.rss.getRegionsInTransitionInRS().remove(this.regionInfo.getEncodedNameAsBytes(), <END> Boolean.FALSE); } }</code><technical_language>need do dance remove failure done elsewhere</technical_language>

Target:
public void process() { try { String name = regionInfo.getEncodedName(); LOG.trace("Processing close of {}", name); String encodedRegionName = regionInfo.getEncodedName(); HRegion region = (HRegion)rsServices.getRegion(encodedRegionName); if (region == null) { LOG.warn("Received CLOSE for region but currently not serving - ignoring", name); return; } try { if (region.close(abort) == null) { LOG.warn("Can't close region {}, was already closed during close()", name); return; } } catch (IOException ioe) { server.abort("Unrecoverable exception while closing region " + regionInfo.getRegionNameAsString() + ", still finishing close", ioe); throw new RuntimeException(ioe); } this.rsServices.removeRegion(region, destination); rsServices.reportRegionStateTransition(new RegionStateTransitionContext(TransitionCode.CLOSED, HConstants.NO_SEQNUM, Procedure.NO_PROC_ID, -1, regionInfo)); LOG.debug("Closed " + region.getRegionInfo().getRegionNameAsString()); } finally { this.rsServices.getRegionsInTransitionInRS(). remove(this.regionInfo.getEncodedNameAsBytes(), Boolean.FALSE); } }
Source:
<code>private List<AppInfo> fetchAppInfosAndStatistics() { List<AppInfo> apps = fetchAppInfos(); int total = apps.size(); final Object lock = new Object(); fetchAppInfoCounter = 0; for (final AppInfo app : apps) { new Thread(new Runnable() { @Override public void run() { <START> AppStats stats = app.getLatestStats(); <END> fetchRatings(app, stats); stats.setNumberOfComments(fetchCommentsCount(app, Utils.getDisplayLocale())); RevenueSummary revenue = fetchRevenueSummary(app); app.setTotalRevenueSummary(revenue); if (revenue != null) { stats.setTotalRevenue(revenue.getLastDay()); } synchronized (lock) { fetchAppInfoCounter++; lock.notify(); } } }).start(); } synchronized (lock) { while (fetchAppInfoCounter < total) { try { lock.wait(); } catch (InterruptedException e) { } } } return apps; }</code><technical_language>This other fetch getDataFromConsole method throw a number of RuntimeExceptions. need caught re-thrown called fetchAppInfosAndStatistics. stop other refreshes</technical_language>

Target:
private List<AppInfo> fetchAppInfosAndStatistics() { ExecutorService executor = Executors.newFixedThreadPool(10); List<AppInfo> apps = fetchAppInfos(); fetchAppInfoCounter = new CountDownLatch(apps.size()); for (final AppInfo app : apps) { Thread thread = new Thread(new Runnable() { @Override public void run() { try { Log.d("start app", app.getName()); AppStats stats = app.getLatestStats(); fetchRatings(app, stats); stats.setNumberOfComments(fetchCommentsCount(app, Utils.getDisplayLocale())); RevenueSummary revenue = fetchRevenueSummary(app); app.setTotalRevenueSummary(revenue); if (revenue != null) { stats.setTotalRevenue(revenue.getLastDay()); } Log.d("end app", app.getName()); } finally { Log.w("finally app", app.getName()); synchronized (fetchAppInfoCounter) { Log.e("fetch counter", String.valueOf(fetchAppInfoCounter.getCount())); fetchAppInfoCounter.countDown(); Log.w("finally count", String.valueOf(fetchAppInfoCounter.getCount())); } } } }); executor.execute(thread); } try { Log.e("Waiting", "waiting..."); fetchAppInfoCounter.await(); } catch (InterruptedException e) { } Log.e("Waiting", "DONE!"); return apps; }
Source:
<code>public void cleanUpEnvironment() { <START> fTrace.dispose(); <END> fScriptingMarkerSource.dispose(); fScriptingMarkerSource = null; fScriptingMarkerSourceFactory.dispose(); fTraceMarkerScriptingModule = null; }</code><technical_language>Technically, need null-check ftrace, other fields, test fails, line exploded, this method is called, is null</technical_language>

Target:
public void cleanUpEnvironment() { if (fTrace != null) { fTrace.dispose(); fTrace = null; } if (fScriptingMarkerSource != null) { fScriptingMarkerSource.dispose(); fScriptingMarkerSource = null; } if (fScriptingMarkerSourceFactory != null) { fScriptingMarkerSourceFactory.dispose(); fScriptingMarkerSourceFactory = null; } }
Source:
<code>public void testLargeMessagePutWithDropLargeMessageDisabled() { LargeMessageSafeStore largeMessageSafeKeyValueStore = new LargeMessageSafeStore(store, storeName, false, maxMessageSize); byte[] key1 = new byte[16]; byte[] smallMessage = new byte[32]; largeMessageSafeKeyValueStore.put(key1, smallMessage); Mockito.verify(store).put(Matchers.eq(key1), Matchers.eq(smallMessage)); byte[] key2 = new byte[16]; byte[] largeMessage = new byte[maxMessageSize + 1]; try { largeMessageSafeKeyValueStore.put(key2, largeMessage); Assert.fail("The test case should have failed due to a large message being passed to the changelog, but it didn't."); <START> } catch (SamzaException e) { <END> Mockito.verifyZeroInteractions(store); } }</code><technical_language>check for RecordTooLargeException instead of SamzaException</technical_language>

Target:
public void testLargeMessagePutWithDropLargeMessageDisabled() { LargeMessageSafeStore largeMessageSafeKeyValueStore = new LargeMessageSafeStore(store, storeName, false, maxMessageSize); byte[] key = new byte[16]; byte[] largeMessage = new byte[maxMessageSize + 1]; try { largeMessageSafeKeyValueStore.put(key, largeMessage); Assert.fail("The test case should have failed due to a large message being passed to the changelog, but it didn't."); } catch (RecordTooLargeException e) { Mockito.verifyZeroInteractions(store); } }
Source:
<code>public String toString() { <START> return String.format("RaftJournalSystem, in quorum: {%s}", mConf.getClusterAddresses().stream() <END> .map(Object::toString).collect(Collectors.joining(","))); }</code><technical_language>MoreObjects.toStringHelper() for this</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("Quorum-Members", mConf.getClusterAddresses().stream() .map(Object::toString).collect(Collectors.joining(", "))) .toString(); }
Source:
<code>public boolean hasCoverage() { CoverageResult result = getCoverageResult(); <START> if (result == null) { <END> return false; } return result.getCoverage(CoverageMetric.LINE) != null; }</code><technical_language>return result != null && result.getCoverage(CoverageMetric.LINE) != null;</technical_language>

Target:
public boolean hasCoverage() { CoverageResult result = getCoverageResult(); return result != null && result.getCoverage(CoverageMetric.LINE) != null; }
Source:
<code>public WorkspaceDto updateEnvironment(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The name of the environment") @PathParam("name") String envName, @ApiParam(value = "The environment update", required = true) EnvironmentDto update, @ApiParam("New name of the environment") @QueryParam("new-name") String newEnvName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { requiredNotNull(update, "Environment description"); relativizeRecipeLinks(update); final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); EnvironmentImpl previous = workspace.getConfig().getEnvironments().remove(envName); if (previous == null) { throw new NotFoundException(format("Workspace '%s' doesn't contain environment '%s'", id, envName)); } <START> if (newEnvName != null && !"".equals(newEnvName)) { <END> if (workspace.getConfig().getEnvironments().containsKey(newEnvName)) { throw new ConflictException(format("Environment '%s' already exists", newEnvName)); } envName = newEnvName; } workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(update)); validator.validateConfig(workspace.getConfig()); return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(id, workspace)), getServiceContext()); }</code><technical_language>isNullOrEmpty</technical_language>

Target:
public WorkspaceDto updateEnvironment(@ApiParam("The workspace id") @PathParam("id") String id, @ApiParam("The name of the environment") @PathParam("name") String envName, @ApiParam(value = "The environment update", required = true) EnvironmentDto update, @ApiParam("New name of the environment") @QueryParam("new-name") String newEnvName) throws ServerException, BadRequestException, NotFoundException, ConflictException, ForbiddenException { requiredNotNull(update, "Environment description"); relativizeRecipeLinks(update); final WorkspaceImpl workspace = workspaceManager.getWorkspace(id); EnvironmentImpl previous = workspace.getConfig().getEnvironments().remove(envName); if (previous == null) { throw new NotFoundException(format("Workspace '%s' doesn't contain environment '%s'", id, envName)); } if (!isNullOrEmpty(newEnvName)) { if (workspace.getConfig().getEnvironments().containsKey(newEnvName)) { throw new ConflictException(format("Environment '%s' already exists in '%s' workspace", newEnvName, workspace.getId())); } envName = newEnvName; } workspace.getConfig().getEnvironments().put(envName, new EnvironmentImpl(update)); validator.validateConfig(workspace.getConfig()); return linksInjector.injectLinks(asDto(workspaceManager.updateWorkspace(id, workspace)), getServiceContext()); }
Source:
<code>public boolean isResolved() { <START> for (Dependency dep : dependencies) { <END> if (!dep.isResolved()) return false; } return true; }</code><technical_language>This logic moved Dependencies class</technical_language>

Target:
public boolean isResolved() { return dependencies.isResolved(); }