auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean timeToDelete(HostAndPort address, long wait) { Long firstSeen = firstSeenDead.get(address); if (firstSeen != null) { <START> long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - firstSeen); <END> log.trace("Elapsed seconds since " + address + " first seen dead: " + elapsedTime); return elapsedTime > wait; } else { log.trace("Adding server to firstSeenDead map " + address); firstSeenDead.put(address, System.nanoTime()); return false; } }</code><technical_language>Log message claims seconds code prints millis</technical_language>

Target:
protected boolean timeToDelete(HostAndPort address, long wait) { Long firstSeen = firstSeenDead.get(address); if (firstSeen != null) { long elapsedTime = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - firstSeen); log.trace("Elapsed milliseconds since " + address + " first seen dead: " + elapsedTime); return elapsedTime > wait; } else { log.trace("Adding server to firstSeenDead map " + address); firstSeenDead.put(address, System.nanoTime()); return false; } }
Source:
<code>@Override public View getView(int position, View convertView, ViewGroup parent) { SquaredImageView view = (SquaredImageView) convertView; if (view == null) { view = new SquaredImageView(context); view.setScaleType(CENTER_CROP); } String url = getItem(position); RequestCreator creator = Picasso.with(context) .load(url) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .fit(); if (useShaderEffects) { <START> creator.transformTarget(new TargetTransformation() { <END> @Override public Drawable transform(Bitmap source) { return new ShaderEffectsDrawable(source); } }); } creator.into(view); return view; }</code><technical_language>Wasteful allocation of this function. Create store in a field</technical_language>

Target:
@Override public View getView(int position, View convertView, ViewGroup parent) { SquaredImageView view = (SquaredImageView) convertView; if (view == null) { view = new SquaredImageView(context); view.setScaleType(CENTER_CROP); } String url = getItem(position); RequestCreator creator = Picasso.with(context) .load(url) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .fit(); if (drawableFactory != null) { creator.drawableFactory(drawableFactory); } creator.into(view); return view; }
Source:
<code>public boolean isInstanceWithSameNameExists(String name) { <START> return DbFacade.getInstance().getVmTemplateDao().getInstanceByName(name, null, false) != null; <END> }</code><technical_language>please inject DAO</technical_language>

Target:
public boolean isInstanceWithSameNameExists(String name) { return vmTemplateDao.getInstanceTypeByName(name, null, false) != null; }
Source:
<code>void setStreamCodec(StreamCodec<?> streamCodec) { if (streamCodec != null) { StreamCodec<?> oldStreamCodec = attributes.put(STREAM_CODEC, streamCodec); <START> if (oldStreamCodec != null && oldStreamCodec != streamCodec) { <END> throw new RuntimeException(String.format("Failed to set stream codec to %s. Input port %s stream codec is already set to %s.", streamCodec, this, oldStreamCodec)); } } }</code><technical_language>checks needed? checks in addInputPort method. set attribute this is a public method</technical_language>

Target:
void setStreamCodec(StreamCodec<?> streamCodec) { if (streamCodec != null) { StreamCodec<?> oldStreamCodec = attributes.put(STREAM_CODEC, streamCodec); if (oldStreamCodec != null && oldStreamCodec != streamCodec) { LOG.warn("Input port stream codec was changed from to {}", this.getPortName(), oldStreamCodec, streamCodec); } } }
Source:
<code>public void connect() throws IOException { <START> throw new IOException(); <END> }</code><technical_language>I suggest simply</technical_language>

Target:
public void connect() throws IOException
Source:
<code><START> public FormValidation doCheckApplication(@QueryParameter String credential, @QueryParameter final String value, @AncestorInPath AbstractProject<?, ?> project) { <END> if (project == null) { if (!project.hasPermission(Jenkins.ADMINISTER)) { return FormValidation.ok(); } } else if (!project.hasPermission(Item.EXTENDED_READ) && !project.hasPermission(CredentialsProvider.USE_ITEM)) { return FormValidation.ok(); } project.checkPermission(AbstractProject.CONFIGURE); if ("Applications/".equals(value)) return ok("Fill in the application ID, eg Applications/PetClinic"); String resolvedName = expandValue(value, project); final String applicationName = DeployitServerFactory.getNameFromId(resolvedName); Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String candidate : candidates) { if (candidate.endsWith("/" + applicationName)) { return ok(); } } if (!candidates.isEmpty()) { return warning("Application does not exist, but will be created upon package import. Did you mean to type one of the following: %s?", candidates); } return warning("Application does not exist, but will be created upon package import."); }</code><technical_language>@RequirePOST this appears open a network connection</technical_language>

Target:
public FormValidation doCheckApplication(@QueryParameter String credential, @QueryParameter final String value, @AncestorInPath AbstractProject<?, ?> project) { project.checkPermission(Jenkins.ADMINISTER); if ("Applications/".equals(value)) return ok("Fill in the application ID, eg Applications/PetClinic"); String resolvedName = expandValue(value, project); final String applicationName = DeployitServerFactory.getNameFromId(resolvedName); Credential overridingcredential = RepositoryUtils.retrieveOverridingCredentialFromProject(project); DeployitServer deployitServer = RepositoryUtils.getDeployitServer(credential, overridingcredential, project); List<String> candidates = deployitServer.search(DeployitDescriptorRegistry.UDM_APPLICATION, applicationName + "%"); for (String candidate : candidates) { if (candidate.endsWith("/" + applicationName)) { return ok(); } } if (!candidates.isEmpty()) { return warning("Application does not exist, but will be created upon package import. Did you mean to type one of the following: %s?", candidates); } return warning("Application does not exist, but will be created upon package import."); }
Source:
<code>private char[] loadValueFromStore(final String variableKey) { try { final KeyStore ks = getSecretsStore(); <START> if (ks.containsAlias(variableKey)) { <END> final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); final SecretKeyFactory factory = SecretKeyFactory.getInstance( SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final SecretKeyEntry secretKeyEntry = (SecretKeyEntry) ks.getEntry(variableKey, keyStorePP); return ((PBEKeySpec) factory.getKeySpec(secretKeyEntry.getSecretKey(), PBEKeySpec.class)).getPassword(); } else { return CACHE_404; } } catch (Exception e) { throw new DotRuntimeException(e); } }</code><technical_language>need .toLowerCase()?, I thought keys saved lowercase in keystore</technical_language>

Target:
private char[] loadValueFromStore(final String variableKey) { try { final KeyStore keyStore = getSecretsStore(); if (keyStore.containsAlias(variableKey)) { final PasswordProtection keyStorePP = new PasswordProtection(loadStorePassword()); final SecretKeyFactory factory = SecretKeyFactory.getInstance(SECRETS_STORE_SECRET_KEY_FACTORY_TYPE); final SecretKeyEntry secretKeyEntry = (SecretKeyEntry) keyStore.getEntry(variableKey, keyStorePP); return ((PBEKeySpec) factory.getKeySpec(secretKeyEntry.getSecretKey(), PBEKeySpec.class)).getPassword(); } else { return CACHE_404; } } catch (Exception e) { Logger.error(SecretsStoreKeyStoreImpl.class,e); throw new DotRuntimeException(e); } }
Source:
<code>private void auditRequest(PRPAIN201305UV02 request, AssertionType assertion, NhinTargetSystemType target) { <START> getNewPatientDiscoveryAuditLogger().auditRequestMessage(request, assertion, target, <END> NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE, Boolean.TRUE, null, NhincConstants.PATIENT_DISCOVERY_SERVICE_NAME); }</code><technical_language>call this "getAuditLogger" for other services? I thinking of a function</technical_language>

Target:
private void auditRequest(PRPAIN201305UV02 request, AssertionType assertion, NhinTargetSystemType target) { getAuditLogger().auditRequestMessage(request, assertion, target, NhincConstants.AUDIT_LOG_OUTBOUND_DIRECTION, NhincConstants.AUDIT_LOG_NHIN_INTERFACE, Boolean.TRUE, null, NhincConstants.PATIENT_DISCOVERY_SERVICE_NAME); }
Source:
<code>public void execute(TopicEvent<ClusteredAgentRequest> event) { <START> ClusteredAgentRequest agentRequest = event.getData(); <END> if (agentRequest.getRequestType().equals(EXPIRE_LOCAL_CACHE)) { expireLocalCache(); } else { if (event.getKey().equals(getConfig().getRegion())) { AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName()); if (agentIdentity != null) { agentRequest.getRequestType().process(ClusteredAgentManagerService.this, agentIdentity); } } } }</code><technical_language>return remove else below</technical_language>

Target:
public void execute(TopicEvent<ClusteredAgentRequest> event) { ClusteredAgentRequest agentRequest = event.getData(); if (agentRequest.getRequestType().equals(EXPIRE_LOCAL_CACHE)) { expireLocalCache(); return; } if (event.getKey().equals(getConfig().getRegion())) { AgentControllerIdentityImplementation agentIdentity = getAgentIdentityByIpAndName(agentRequest.getAgentIp(), agentRequest.getAgentName()); if (agentIdentity != null) { agentRequest.getRequestType().process(ClusteredAgentManagerService.this, agentIdentity); } } }
Source:
<code>public void check(Message message, Topic topic) { if (ContentType.JSON != topic.getContentType() || !topic.isValidationEnabled()) { return; } <START> List<String> errors = validate(message.<JsonSchema>getSchema().get().getSchema(), message.getData()); <END> if (!errors.isEmpty()) { if (topic.isValidationDryRunEnabled()) { logger.info("Message incompatible with JSON schema for topic {}, errors: {}, message body: {}", topic.getQualifiedName(), Joiner.on(";").join(errors), new String(message.getData(), UTF_8)); } else { throw new InvalidMessageException("Message incompatible with JSON schema", errors); } } }</code><technical_language>too, getSchema().get().getSchema() feels insane</technical_language>

Target:
public void check(Message message, Topic topic) { if (ContentType.JSON != topic.getContentType() || !topic.isValidationEnabled()) { return; } List<String> errors = validate(message.<JsonSchema>getCompiledSchema(), message.getData()); if (!errors.isEmpty()) { if (topic.isValidationDryRunEnabled()) { logger.info("Message incompatible with JSON schema for topic {}, errors: {}, message body: {}", topic.getQualifiedName(), Joiner.on(";").join(errors), new String(message.getData(), UTF_8)); } else { throw new InvalidMessageException("Message incompatible with JSON schema", errors); } } }
Source:
<code>public String getEventName(ITimeEvent event) { State state = getEventState(event); if (state != null) { return state.toString(); <START> } <END> return null; }</code><technical_language>a case ResourcesView_multipleStates is returned</technical_language>

Target:
public String getEventName(ITimeEvent event) { State state = getEventState(event); if (state != null) { return state.toString(); } if (event instanceof TimeEvent) { TimeEvent tcEvent = (TimeEvent) event; if (tcEvent.hasValue()) { return null; } } return Messages.ResourcesView_multipleStates; }
Source:
<code>public final Opt<Identity> enter(final Request request) throws IOException { for (final Pass pass : this.all) { final Opt<Identity> enter = pass.enter(request); if (!enter.has()) { break; } <START> } <END> final Opt<Identity> result; if (this.index < this.all.size()) { result = this.all.get(this.index).enter(request); } else { result = new Opt.Empty<Identity>(); } return result; }</code><technical_language>@lautarobock is wrong here.. this loop is totally useless. result anywhere. simply remove change</technical_language>

Target:
public final Opt<Identity> enter(final Request request) throws IOException { boolean success = true; for (final Pass pass : this.all) { final Opt<Identity> enter = pass.enter(request); if (!enter.has()) { success = false; } } final Opt<Identity> result; if (success && this.index < this.all.size()) { result = this.all.get(this.index).enter(request); } else { result = new Opt.Empty<Identity>(); } return result; }
Source:
<code>MetricsQuery checkAndAddMergeAggregator(final MetricsQuery metricsQuery) { final List<Metric> newMetrics = new ArrayList<>(); for (final Metric metric : metricsQuery.getMetrics()) { if (needMergeAggregator(metric.getAggregators())) { final List<Aggregator> newAggregators = new ArrayList<>(); final Optional<Aggregator> aggregatorWithSampling = metric.getAggregators().stream().filter( aggregator -> aggregator.getSampling().isPresent()).findFirst(); <START> newAggregators.add(aggregatorWithSampling.map( <END> aggregator -> ThreadLocalBuilder.clone(aggregator, Aggregator.Builder.class, b -> b.setName("merge"))). orElseGet(() -> ThreadLocalBuilder.build(Aggregator.Builder.class, b -> b.setName("merge")))); newAggregators.addAll(metric.getAggregators()); final ImmutableList<Aggregator> finalNewAggregators = ImmutableList.copyOf(newAggregators); newMetrics.add(ThreadLocalBuilder.clone( metric, Metric.Builder.class, b->b.setAggregators(finalNewAggregators))); } else { newMetrics.add(metric); } } final ImmutableList<Metric> finalNewMetrics = ImmutableList.copyOf(newMetrics); return ThreadLocalBuilder.clone(metricsQuery, MetricsQuery.Builder.class, b->b.setMetrics(finalNewMetrics)); }</code><technical_language>If aggregator parameters (e.g. percentile value) apply merge aggregator, clear them. point here, is I suspect is construct a new MergeAggregator definition clone a random target get sampling</technical_language>

Target:
MetricsQuery checkAndAddMergeAggregator(final MetricsQuery metricsQuery) { final List<Metric> newMetrics = new ArrayList<>(); for (final Metric metric : metricsQuery.getMetrics()) { if (needMergeAggregator(metric.getAggregators())) { final List<Aggregator> newAggregators = new ArrayList<>(); final Optional<Aggregator> aggregatorWithSampling = metric.getAggregators().stream().filter( aggregator -> aggregator.getSampling().isPresent()).findFirst(); newAggregators.add(aggregatorWithSampling.map( aggregator -> ThreadLocalBuilder.build(Aggregator.Builder.class, b -> { b.setName("merge"); aggregator.getSampling().ifPresent(b::setSampling); aggregator.getAlignStartTime().ifPresent(b::setAlignStartTime); aggregator.getAlignSampling().ifPresent(b::setAlignSampling); aggregator.getAlignEndTime().ifPresent(b::setAlignEndTime); })). orElseGet(() -> ThreadLocalBuilder.build(Aggregator.Builder.class, b -> b.setName("merge")))); newAggregators.addAll(metric.getAggregators()); final ImmutableList<Aggregator> finalNewAggregators = ImmutableList.copyOf(newAggregators); newMetrics.add(ThreadLocalBuilder.clone( metric, Metric.Builder.class, b->b.setAggregators(finalNewAggregators))); } else { newMetrics.add(metric); } } final ImmutableList<Metric> finalNewMetrics = ImmutableList.copyOf(newMetrics); return ThreadLocalBuilder.clone(metricsQuery, MetricsQuery.Builder.class, b->b.setMetrics(finalNewMetrics)); }
Source:
<code>private String parseHost(final String url) { <START> HttpUrl httpUrl = HttpUrl.parse(url); <END> if (httpUrl == null) { throw new IllegalArgumentException("Unable to parse url: " + url); } String hostName = httpUrl.host(); try { InetAddress.getByName(hostName); } catch (UnknownHostException e) { throw new InfluxDBIOException(e); } return hostName; }</code><technical_language>Is HttpUrl able parse URIs do start string http? IMO treat this parameter URI URL. main reasons are: * Users finally stop scheme "http://" connect UDP. [RFC 1738 for URL](<LINK_0> allow scheme "udp://" [RFC 3986 for URI](<LINK_1> does. * If so, this line replaced URI.create(...) URI#getHost() get hostname</technical_language>

Target:
private String parseHost(final String url) { String hostName; try { URI uri = new URI(url); hostName = uri.getHost(); } catch (URISyntaxException e1) { throw new IllegalArgumentException("Unable to parse url: " + url, e1); } if (hostName == null) { throw new IllegalArgumentException("Unable to parse url: " + url); } try { InetAddress.getByName(hostName); } catch (UnknownHostException e) { throw new InfluxDBIOException(e); } return hostName; }
Source:
<code>private void processPackAnnotation(DescriptorPolicy descriptorPolicy) { ConstraintConfiguration packAnnotation = constraintConfigurationClass.getAnnotation(ConstraintConfiguration.class); constraintPackage = packAnnotation.constraintPackage(); if (constraintPackage.equals("")) { constraintPackage = constraintConfigurationClass.getPackage().getName(); } <START> if (packAnnotation == null) { <END> throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass + ") has been specified as a " + ConstraintConfigurationProvider.class.getSimpleName() + " in the solution class (" + solutionDescriptor.getSolutionClass() + ")," + " but does not have a " + ConstraintConfiguration.class.getSimpleName() + " annotation."); } }</code><technical_language>Findbugs: > Nullcheck of packAnnotation line 103 of previously dereferenced. nullcheck of packAnnotation happen is line 103</technical_language>

Target:
private void processPackAnnotation(DescriptorPolicy descriptorPolicy) { ConstraintConfiguration packAnnotation = constraintConfigurationClass.getAnnotation(ConstraintConfiguration.class); if (packAnnotation == null) { throw new IllegalStateException("The constraintConfigurationClass (" + constraintConfigurationClass + ") has been specified as a " + ConstraintConfigurationProvider.class.getSimpleName() + " in the solution class (" + solutionDescriptor.getSolutionClass() + ")," + " but does not have a " + ConstraintConfiguration.class.getSimpleName() + " annotation."); } }
Source:
<code>private SynapseCORSConfiguration() { enabled = SynapsePropertiesLoader.getBooleanProperty(RESTConstants.CORS_CONFIGURATION_ENABLED, true); String allowedOriginListStr = SynapsePropertiesLoader.getPropertyValue(RESTConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN, ""); String[] originList = allowedOriginListStr.split(","); for (String origin : originList) { String trimmedOrigin = origin.trim(); allowedOrigins.add(trimmedOrigin); try { URL url = new URL(trimmedOrigin); if (url.getHost().equals("localhost")) { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface nInterface = networkInterfaces.nextElement(); for (InterfaceAddress iAddr : nInterface.getInterfaceAddresses()) { URL localUrl = new URL(url.getProtocol(), iAddr.getAddress().getHostAddress(), url.getPort(), ""); allowedOrigins.add(localUrl.toString()); } } } } catch (MalformedURLException e) { <START> LOG.error("Provided origin URL "+ trimmedOrigin + " is malformed", e); <END> } catch (SocketException e) { LOG.error("Error occurred while retrieving network interfaces", e); } } allowedHeaders = SynapsePropertiesLoader.getPropertyValue(RESTConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS, ""); }</code><technical_language>logging is enough here</technical_language>

Target:
private SynapseCORSConfiguration() { enabled = SynapsePropertiesLoader.getBooleanProperty(RESTConstants.CORS_CONFIGURATION_ENABLED, true); String allowedOriginListStr = SynapsePropertiesLoader.getPropertyValue(RESTConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_ORIGIN, null); if (allowedOriginListStr != null) { String[] originList = allowedOriginListStr.split(","); for (String origin : originList) { String trimmedOrigin = origin.trim(); allowedOrigins.add(trimmedOrigin); try { URL url = new URL(trimmedOrigin); if (url.getHost().equals("localhost")) { Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces(); while (networkInterfaces.hasMoreElements()) { NetworkInterface nInterface = networkInterfaces.nextElement(); for (InterfaceAddress iAddr : nInterface.getInterfaceAddresses()) { URL localUrl = new URL(url.getProtocol(), iAddr.getAddress().getHostAddress(), url.getPort(), ""); allowedOrigins.add(localUrl.toString()); } } } } catch (MalformedURLException e) { throw new SynapseException("Provided origin URL " + trimmedOrigin + " is malformed", e); } catch (SocketException e) { throw new SynapseException("Error occurred while retrieving network interfaces", e); } } } allowedHeaders = SynapsePropertiesLoader.getPropertyValue(RESTConstants.CORS_CONFIGURATION_ACCESS_CTL_ALLOW_HEADERS, ""); }
Source:
<code>protected CommandStatus run() { for (int i = 0; i < commandConfig.getSplitCommand().size(); i++) { if (status == CommandStatus.CANCELED) { logger.info("Job has been canceled, quitting now."); break; } String thisCommand = commandConfig.getSplitCommand().get(i); status = setupProcessBuilder(thisCommand); status = processJob(); status = finishJob(); try { checkStatus(status); } catch (IOException e) { <START> e.printStackTrace(); <END> return CommandStatus.FAILED; } if (status != CommandStatus.SUCCESS && status != CommandStatus.FAILED) { logger.info("Monitoring job"); status = monitorJob(); } try { checkStatus(status); } catch (IOException e) { e.printStackTrace(); return CommandStatus.FAILED; } } try { commandConfig.getStdOut().close(); commandConfig.getStdErr().close(); } catch (IOException e) { status = CommandStatus.INFOERROR; logger.error("Could not close the output and/or error files, returning INFOERROR"); return status; } return status; }</code><technical_language>logged not</technical_language>

Target:
protected CommandStatus run() { for (int i = 0; i < commandConfig.getSplitCommand().size(); i++) { if (status == CommandStatus.CANCELED) { logger.info("Job has been canceled, quitting now."); break; } String thisCommand = commandConfig.getSplitCommand().get(i); status = setupProcessBuilder(thisCommand); status = processJob(); status = finishJob(); if (!checkStatus(status)) return CommandStatus.FAILED; if (status != CommandStatus.SUCCESS && status != CommandStatus.FAILED) { logger.info("Monitoring job"); status = monitorJob(); } if (!checkStatus(status)) return CommandStatus.FAILED; } try { commandConfig.getStdOut().close(); commandConfig.getStdErr().close(); } catch (IOException e) { status = CommandStatus.FAILED; logger.error("Could not close the output and/or error files, returning INFOERROR", e); return status; } return status; }
Source:
<code>public void testChangeHeaderAfterWritingHeader() { final File fakeVCFFile = VariantBaseTest.createTempFile("testBasicWriteAndRead.", ".vcf"); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); final VariantContextWriter writer2 = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile) .setReferenceDictionary(sequenceDict) .build(); writer2.writeHeader(header); writer2.setVCFHeader(header); <START> writer2.close(); <END> }</code><technical_language>try</technical_language>

Target:
public void testChangeHeaderAfterWritingHeader() { final File fakeVCFFile = VariantBaseTest.createTempFile("testBasicWriteAndRead.", ".vcf"); fakeVCFFile.deleteOnExit(); final SAMSequenceDictionary sequenceDict = createArtificialSequenceDictionary(); final VCFHeader header = createFakeHeader(metaData, additionalColumns, sequenceDict); try (final VariantContextWriter writer2 = new VariantContextWriterBuilder() .setOutputFile(fakeVCFFile) .setReferenceDictionary(sequenceDict) .build()) { writer2.writeHeader(header); writer2.setVCFHeader(header); } }
Source:
<code>private void setupSuggestionServiceAndAdapter() { if (!isAdded()) return; int remoteBlogId = -1; String blogID = WordPress.getCurrentRemoteBlogId(); remoteBlogId = StringUtils.stringToInt(blogID, -1); mSuggestionServiceConnectionManager = new SuggestionServiceConnectionManager(getActivity(), remoteBlogId); mTagSuggestionAdapter = SuggestionUtils.setupTagSuggestions(remoteBlogId, getActivity(), mSuggestionServiceConnectionManager); <START> if (mTagSuggestionAdapter != null) { <END> mTags.setAdapter(mTagSuggestionAdapter); } }</code><technical_language>mTagSuggestionAdapter is this method, downgraded a class variable a method variable</technical_language>

Target:
private void setupSuggestionServiceAndAdapter() { if (!isAdded()) return; int remoteBlogId = -1; String blogID = WordPress.getCurrentRemoteBlogId(); remoteBlogId = StringUtils.stringToInt(blogID, -1); mSuggestionServiceConnectionManager = new SuggestionServiceConnectionManager(getActivity(), remoteBlogId); TagSuggestionAdapter tagSuggestionAdapter = SuggestionUtils.setupTagSuggestions(remoteBlogId, getActivity(), mSuggestionServiceConnectionManager); if (tagSuggestionAdapter != null) { mTagsEditText.setAdapter(tagSuggestionAdapter); } }
Source:
<code>public void onWorldLoad(WorldEvent.Load evt) { if (!(evt.getWorld().getWorldType() instanceof ICubicWorldType)) { return; } CubicChunks.LOGGER.info("Initializing world " + evt.getWorld() + " with type " + evt.getWorld().getWorldType()); ICubicWorld world = (ICubicWorld) evt.getWorld(); WorldType type = evt.getWorld().getWorldType(); <START> if(type instanceof ICubicWorldType) { <END> WorldProvider provider = ((ICubicWorldType)type).getReplacedProviderFor(world.getProvider()); world.hotSetProvider(provider); } world.initCubicWorld(); if(!world.isRemote()) { ((ICubicWorldServer)world).generateWorld(); } }</code><technical_language>matter configured, eclipse formatter change IDEA change. I try settings for eclipse IDEA reformat code hard for now</technical_language>

Target:
public void onWorldLoad(WorldEvent.Load evt) { if (!(evt.getWorld().getWorldType() instanceof ICubicWorldType)) { return; } CubicChunks.LOGGER.info("Initializing world " + evt.getWorld() + " with type " + evt.getWorld().getWorldType()); ICubicWorld world = (ICubicWorld) evt.getWorld(); WorldType type = evt.getWorld().getWorldType(); if(type instanceof ICubicWorldType) { WorldProvider provider = ((ICubicWorldType)type).getReplacedProviderFor(world.getProvider()); ReflectionUtil.setFieldValueSrg(world, "field_73011_w", provider); } world.initCubicWorld(); if(!world.isRemote()) { ((ICubicWorldServer)world).generateWorld(); } }
Source:
<code>public long getAuditorLedgerVerificationPercentage() { <START> return getLong(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, 100); <END> }</code><technical_language>default 0, default this feature is enabled</technical_language>

Target:
public long getAuditorLedgerVerificationPercentage() { return getLong(AUDITOR_LEDGER_VERIFICATION_PERCENTAGE, 0); }
Source:
<code>public void updated(final Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { final String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { refreshInterval = Long.parseLong(refreshIntervalString); } final String host = (String) config.get("hostname"); <START> if (StringUtils.isNotBlank(host)) { <END> this.hostname = host; } final String port = (String) config.get("port"); if (StringUtils.isNotBlank(port)) { this.port = Integer.parseInt(port); } setProperlyConfigured(true); } }</code><technical_language>throw a ConfigurationException in this case infer a reasonable default hostname here, right</technical_language>

Target:
public void updated(final Dictionary<String, ?> config) throws ConfigurationException { if (config != null) { final String refreshIntervalString = (String) config.get("refresh"); if (StringUtils.isNotBlank(refreshIntervalString)) { try { refreshInterval = Long.parseLong(refreshIntervalString); } catch (NumberFormatException e) { throw new ConfigurationException( "refresh", String.format( "Provided value (%s) cannot be parsed to an long integer.", port)); } } final String host = (String) config.get("hostname"); if (StringUtils.isNotBlank(host)) { this.hostname = host; } else { throw new ConfigurationException("hostname", "Required configuration parameter is not set."); } final String port = (String) config.get("port"); if (StringUtils.isNotBlank(port)) { try { this.port = Integer.parseInt(port); } catch (NumberFormatException e) { throw new ConfigurationException( "port", String.format( "Provided value (%s) cannot be parsed to an integer.", port)); } } setProperlyConfigured(true); } }
Source:
<code><START> public void pause() throws IOException { <END> this.client.call( LuaCommand.PAUSE.toString(), this.name); this.client.call( LuaCommand.TIMEOUT.toString(), this.jobs().running(0, -1)); }</code><technical_language>This optionally timeout jobs. java public void pause(final boolean timeoutRunningJobs) throws IOException { // Invoke pause if (timeoutRunningJobs) { // Invoke timeout } }</technical_language>

Target:
public void pause() throws IOException { this.pause(true); }
Source:
<code>public void testRequiredSerializedNameMissing() { <START> SerializedNameModel result = unmarshal(SerializedNameModel.class, "{}"); <END> assertThat(result, nullValue()); }</code><technical_language>For missing cases, consistent. "{}" marshal(expected)</technical_language>

Target:
public void testRequiredSerializedNameMissing() { SerializedNameModel result = unmarshal(gson, SerializedNameModel.class, "{}"); assertThat(result, nullValue()); }
Source:
<code>public void testMergeDetachedOrphanRemoval() { final Root entity = doInHibernate( this::sessionFactory, session -> { Root root = new Root(); root.setName( "new" ); session.save( root ); return root; } ); doInHibernate( this::sessionFactory, session -> { entity.setName( "updated" ); Root entityMerged = (Root) session.merge( entity ); assertNotSame( entity, entityMerged ); <START> assertNotSame( entity, entityMerged ); <END> assertNotSame( entity.getLeaves(), entityMerged.getLeaves() ); } ); }</code><technical_language>test this twice</technical_language>

Target:
public void testMergeDetachedOrphanRemoval() { final Root entity = doInHibernate( this::sessionFactory, session -> { Root root = new Root(); root.setName( "new" ); session.save( root ); return root; } ); doInHibernate( this::sessionFactory, session -> { entity.setName( "updated" ); Root entityMerged = (Root) session.merge( entity ); assertNotSame( entity, entityMerged ); assertNotSame( entity.getLeaves(), entityMerged.getLeaves() ); } ); }
Source:
<code>public void start(BundleContext bc) throws Exception { <START> if (webDavHandler == null) { <END> webDavHandler = WebDavHandler.getInstance(); } webDavHandler.setBundleContext(bc); webDavHandler.start(); }</code><technical_language>if is'nt useful, is it</technical_language>

Target:
public void start(BundleContext bc) throws Exception { webDavHandler = WebDavHandler.getInstance(); webDavHandler.setBundleContext(bc); webDavHandler.start(); }
Source:
<code>public void reportMetric(final IMetric<?> metric) throws Exception { String gangliaCommand = buildCommand(metric); synchronized (metric) { Process emission = Runtime.getRuntime().exec(gangliaCommand); int exitCode = emission.waitFor(); if (exitCode != 0) { throw new RuntimeException("Failed to report metric using gmetric"); } <START> } <END> }</code><technical_language>synchronizing metric String gangliaCommand constructed accessing metric's state all</technical_language>

Target:
public void reportMetric(final IMetric<?> metric) throws MetricException { String gangliaCommand = buildCommand(metric); if (gangliaCommand != null) { try { Process emission = Runtime.getRuntime().exec(gangliaCommand); int exitCode; exitCode = emission.waitFor(); if (exitCode != 0) { throw new MetricException("Failed to report metric using gmetric"); } } catch (Exception e) { throw new MetricException("Failed to report metric using gmetric"); } } else { throw new MetricException("Failed to build ganglia Command"); } }
Source:
<code>public void addLdapAuthentication(UserEntity userEntity, String dn, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.LDAP, StringUtils.lowerCase(dn), <START> new Validator() { <END> @Override public void validate(UserEntity userEntity, String key) throws AmbariException { List<UserAuthenticationEntity> authenticationEntities = userEntity.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if ((entity.getAuthenticationType() == UserAuthenticationType.LDAP) && ((key == null) ? (entity.getAuthenticationKey() == null) : key.equalsIgnoreCase(entity.getAuthenticationKey()))) { throw new AmbariException("The authentication type already exists for this user"); } } } }, persist); }</code><technical_language>do lambda approach</technical_language>

Target:
public void addLdapAuthentication(UserEntity userEntity, String dn, boolean persist) throws AmbariException { addAuthentication(userEntity, UserAuthenticationType.LDAP, StringUtils.lowerCase(dn), (user, key) -> { List<UserAuthenticationEntity> authenticationEntities = user.getAuthenticationEntities(); for (UserAuthenticationEntity entity : authenticationEntities) { if ((entity.getAuthenticationType() == UserAuthenticationType.LDAP) && ((key == null) ? (entity.getAuthenticationKey() == null) : key.equalsIgnoreCase(entity.getAuthenticationKey()))) { throw new AmbariException("The authentication type already exists for this user"); } } }, persist); }
Source:
<code>public RequestBuilder<T> withPath(String path) { String cleanPath = path.startsWith("/") && path.endsWith("/") ? path.substring(1, path.length() - 1) : path.startsWith("/") ? path.substring(1) : path.endsWith("/") ? path.substring(0, path.length() - 1) : path; <START> URL newBaseUrl = url(baseUrl + "/" + cleanPath); <END> return new RequestBuilder<>(method, newBaseUrl, responseMapper, credentials, headers, body, multipartMessages); }</code><technical_language>Is this more readable? <img width="1749" alt="Screen Shot 2019-06-30 11 44 38 AM" src="<LINK_0>"> int start = path.startsWith("/") ? 1 : 0; int end = path.endsWith ("/") ? 1 : 0; String cleanPath = path.substring(start, path.length() - end);</technical_language>

Target:
public RequestBuilder<T> withPath(String path) { int startOffset = path.startsWith("/") ? 1 : 0; int endOffset = path.endsWith("/") ? 1 : 0; String cleanPath = path.substring(startOffset, path.length() - endOffset); URL newBaseUrl = url(baseUrl + "/" + cleanPath); return new RequestBuilder<>(method, newBaseUrl, responseMapper, credentials, headers, body, multipartMessages); }
Source:
<code>private void complete(String msg) { long durationMillis = System.currentTimeMillis() - creationTimeMillis; if (msg == null) { <START> String duration = DurationFormatUtils.formatDurationWords(durationMillis,true, true); <END> msg = String.format("Repair command #%d finished in %s", cmd, duration); } fireProgressEvent(new ProgressEvent(ProgressEventType.COMPLETE, progressCounter.get(), totalProgress, msg)); if (ActiveRepairService.instance.hasParentRepairSession(parentSession)) ActiveRepairService.instance.removeParentRepairSession(parentSession); Context ctx = context; if (options.isTraced() && ctx != null && ctx.traceState != null) { for (ProgressListener listener : listeners) ctx.traceState.removeProgressListener(listener); Tracing.instance.set(ctx.traceState); Tracing.traceRepair(msg); Tracing.instance.stopSession(); } Keyspace.open(keyspace).metric.repairTime.update(durationMillis, TimeUnit.MILLISECONDS); }</code><technical_language>final. Nit: Need space , & true</technical_language>

Target:
private void complete(String msg) { long durationMillis = System.currentTimeMillis() - creationTimeMillis; if (msg == null) { String duration = DurationFormatUtils.formatDurationWords(durationMillis, true, true); msg = String.format("Repair command #%d finished in %s", cmd, duration); } fireProgressEvent(new ProgressEvent(ProgressEventType.COMPLETE, progressCounter.get(), totalProgress, msg)); logger.info(msg); ActiveRepairService.instance.removeParentRepairSession(parentSession); TraceState localState = traceState; if (options.isTraced() && localState != null) { for (ProgressListener listener : listeners) localState.removeProgressListener(listener); Tracing.instance.set(localState); Tracing.traceRepair(msg); Tracing.instance.stopSession(); } Keyspace.open(keyspace).metric.repairTime.update(durationMillis, TimeUnit.MILLISECONDS); }
Source:
<code><START> private String getSequenceNumberInternal(StreamPartition<String> partition, String shardIterator) <END> { long timeoutMillis = System.currentTimeMillis() + fetchSequenceNumberTimeout; while (shardIterator != null && System.currentTimeMillis() < timeoutMillis) { if (closed) { log.info("KinesisRecordSupplier closed while fetching sequenceNumber"); return null; } GetRecordsResult recordsResult; try { recordsResult = kinesis.getRecords(new GetRecordsRequest().withShardIterator(shardIterator).withLimit(1000)); } catch (ProvisionedThroughputExceededException e) { try { Thread.sleep(PROVISIONED_THROUGHPUT_EXCEEDED_BACKOFF_MS); continue; } catch (InterruptedException e1) { log.warn(e1, "Thread interrupted!"); Thread.currentThread().interrupt(); break; } } List<Record> records = recordsResult.getRecords(); if (!records.isEmpty()) { return records.get(0).getSequenceNumber(); } shardIterator = recordsResult.getNextShardIterator(); } if (shardIterator == null) { log.info("Partition[%s] returned a null shard iterator, is the shard closed?", partition.getPartitionId()); return OrderedPartitionableRecord.END_OF_SHARD_MARKER; } log.warn( "timed out while trying to fetch position for shard[%s], likely no more records in shard", partition.getPartitionId() ); return null; }</code><technical_language>Please add Nullable</technical_language>

Target:
private String getSequenceNumberInternal(StreamPartition<String> partition, String shardIterator) { long timeoutMillis = System.currentTimeMillis() + fetchSequenceNumberTimeout; while (shardIterator != null && System.currentTimeMillis() < timeoutMillis) { if (closed) { log.info("KinesisRecordSupplier closed while fetching sequenceNumber"); return null; } GetRecordsResult recordsResult; try { recordsResult = kinesis.getRecords(new GetRecordsRequest().withShardIterator(shardIterator).withLimit(1000)); } catch (ProvisionedThroughputExceededException e) { log.warn( e, "encountered ProvisionedThroughputExceededException while fetching records, this means " + "that the request rate for the stream is too high, or the requested data is too large for " + "the available throughput. Reduce the frequency or size of your requests. Consider increasing " + "the number of shards to increase throughput." ); try { Thread.sleep(PROVISIONED_THROUGHPUT_EXCEEDED_BACKOFF_MS); continue; } catch (InterruptedException e1) { log.warn(e1, "Thread interrupted!"); Thread.currentThread().interrupt(); break; } } List<Record> records = recordsResult.getRecords(); if (!records.isEmpty()) { return records.get(0).getSequenceNumber(); } shardIterator = recordsResult.getNextShardIterator(); } if (shardIterator == null) { log.info("Partition[%s] returned a null shard iterator, is the shard closed?", partition.getPartitionId()); return KinesisSequenceNumber.END_OF_SHARD_MARKER; } log.warn( "timed out while trying to fetch position for shard[%s], likely no more records in shard", partition.getPartitionId() ); return null; }
Source:
<code>public ClientBuilder setPrivateKey(PrivateKey privateKey) { if (isOAuth2Flow()) { Assert.notNull(privateKey, "Missing privateKeyFile"); <START> String encodedString = "-----BEGIN PRIVATE KEY-----\n"; <END> encodedString = encodedString + Base64.getEncoder().encodeToString(privateKey.getEncoded()) + "\n"; encodedString = encodedString + "-----END PRIVATE KEY-----\n"; this.clientConfig.setPrivateKey(encodedString); } return this; }</code><technical_language>RSA private key headers -----BEGIN RSA PRIVATE KEY----- & -----END RSA PRIVATE KEY . Please check if this works other key types support (RSA, EC etc)</technical_language>

Target:
public ClientBuilder setPrivateKey(PrivateKey privateKey) { if (isOAuth2Flow()) { Assert.notNull(privateKey, "Missing privateKeyFile"); String algorithm = privateKey.getAlgorithm(); if (algorithm.equals("RSA")) { String encodedString = ConfigUtil.RSA_PRIVATE_KEY_HEADER + "\n" + Base64.getEncoder().encodeToString(privateKey.getEncoded()) + "\n" + ConfigUtil.RSA_PRIVATE_KEY_FOOTER; this.clientConfig.setPrivateKey(encodedString); } else if(algorithm.equals("EC")) { String encodedString = ConfigUtil.EC_PRIVATE_KEY_HEADER + "\n" + Base64.getEncoder().encodeToString(privateKey.getEncoded()) + "\n" + ConfigUtil.EC_PRIVATE_KEY_FOOTER; this.clientConfig.setPrivateKey(encodedString); } else { throw new IllegalArgumentException("Supplied privateKey is not an RSA or EC key - " + algorithm); } } return this; }
Source:
<code>public void start() { super.workerPool = new TestWorkerService(numWorkerThreads); super.start(); try { <START> Thread.sleep(50); <END> } catch (Exception e){ } LOG.info("numWorkerThreads in Test is {}", numWorkerThreads); }</code><technical_language>Do WorkerService? add another latch join threads here</technical_language>

Target:
public void start() { super.workerPool = new TestWorkerService(numWorkerThreads); super.start(); Thread.State state = super.getState(); while (state != State.WAITING) { try { Thread.sleep(50); } catch (Exception e){ } state = super.getState(); } LOG.info("numWorkerThreads in Test is {}", numWorkerThreads); }
Source:
<code>public void testNestedClass_284665() throws Exception { ICPPClassType b0 = getBindingFromASTName("B {", 1, ICPPClassType.class); assertFalse(b0 instanceof IIndexBinding); ICPPConstructor b1 = getBindingFromASTName("B(int x)", 1, ICPPConstructor.class); assertFalse(b1 instanceof IIndexBinding); ICPPClassType b2 = getBindingFromASTName("B(0)", 1, ICPPClassType.class); <START> assertFalse(b2 instanceof IIndexBinding); <END> assertEquals(b1, b2.getConstructors()[0]); ICPPMethod b3 = getBindingFromASTName("m(0)", 1, ICPPMethod.class); assertFalse(b3 instanceof IIndexBinding); }</code><technical_language>This assertion serve useful purpose removed</technical_language>

Target:
public void testNestedClass_284665() throws Exception { ICPPClassType b0 = getBindingFromASTName("B {", 1, ICPPClassType.class); assertFalse(b0 instanceof IIndexBinding); ICPPConstructor b1 = getBindingFromASTName("B(int x)", 1, ICPPConstructor.class); assertFalse(b1 instanceof IIndexBinding); ICPPClassType b2 = getBindingFromASTName("B(0)", 1, ICPPClassType.class); ICPPMethod b3 = getBindingFromASTName("m(0)", 1, ICPPMethod.class); assertFalse(b3 instanceof IIndexBinding); }
Source:
<code>public void visitJavadocToken(DetailNode detailNode) { DetailNode nextSibling = getNextNode(detailNode); while (nextSibling.getType() == JavadocTokenTypes.DESCRIPTION <START> || nextSibling.getType() == JavadocTokenTypes.WS) { <END> nextSibling = getNextNode(nextSibling); } if (!isLeadingAsterisk(nextSibling) && !isLastLine(nextSibling)) { log(nextSibling.getLineNumber(), MSG_MISSING_ASTERISK); } }</code><technical_language>Please change TokenUtil.isOfType method</technical_language>

Target:
public void visitJavadocToken(DetailNode detailNode) { DetailNode nextSibling = getNextNode(detailNode); while (TokenUtil.isOfType(nextSibling.getType(), JavadocTokenTypes.DESCRIPTION, JavadocTokenTypes.WS)) { nextSibling = getNextNode(nextSibling); } if (!isLeadingAsterisk(nextSibling) && !isLastLine(nextSibling)) { log(nextSibling.getLineNumber(), MSG_MISSING_ASTERISK); } }
Source:
<code>public void shouldReleaseLockForUnassignedTasksAfterRebalance() throws IOException { expectLockObtainedFor(taskId00, taskId01, taskId02); makeTaskFolders( "0_0", "0_1", "0_2" ); replay(stateDirectory); taskManager.handleRebalanceStart(singleton("topic")); assertThat(taskManager.lockedTaskDirectories(), is(mkSet(taskId00, taskId01, taskId02))); <START> handleAssignment(taskId00Assignment, taskId01Assignment, emptyMap()); <END> reset(consumer); expectConsumerAssignmentPaused(consumer); replay(consumer); taskManager.handleRebalanceComplete(); assertThat(taskManager.lockedTaskDirectories(), is(mkSet(taskId00, taskId01))); }</code><technical_language>req: Please verify stateDirectory.unlock("0_2"). verifying lockedTaskDirectories() weak me</technical_language>

Target:
public void shouldReleaseLockForUnassignedTasksAfterRebalance() throws IOException { expectLockObtainedFor(taskId00, taskId01, taskId02); expectUnlockFor(taskId02); makeTaskFolders( taskId00.toString(), taskId01.toString(), taskId02.toString() ); replay(stateDirectory); taskManager.handleRebalanceStart(singleton("topic")); assertThat(taskManager.lockedTaskDirectories(), is(mkSet(taskId00, taskId01, taskId02))); handleAssignment(taskId00Assignment, taskId01Assignment, emptyMap()); reset(consumer); expectConsumerAssignmentPaused(consumer); replay(consumer); taskManager.handleRebalanceComplete(); assertThat(taskManager.lockedTaskDirectories(), is(mkSet(taskId00, taskId01))); verify(stateDirectory); }
Source:
<code>public void isNodeEmpty() { ObjectNode objectNode = new ObjectNode(factory); <START> assertTrue(expressionEvaluatorMock.isNodeEmpty(objectNode)); <END> objectNode.set("key", new TextNode("value")); assertFalse(expressionEvaluatorMock.isNodeEmpty(objectNode)); ArrayNode arrayNode = new ArrayNode(factory); assertTrue(expressionEvaluatorMock.isNodeEmpty(arrayNode)); arrayNode.add(new TextNode("value")); assertFalse(expressionEvaluatorMock.isNodeEmpty(arrayNode)); assertTrue(expressionEvaluatorMock.isNodeEmpty(new TextNode(""))); assertTrue(expressionEvaluatorMock.isNodeEmpty(new TextNode(null))); assertFalse(expressionEvaluatorMock.isNodeEmpty(new TextNode("value"))); }</code><technical_language>please insert this assertion: java objectNode.set("empty array", new ArrayNode(factory)); assertTrue(expressionEvaluatorMock.isNodeEmpty(objectNode));</technical_language>

Target:
public void isNodeEmpty() { ObjectNode objectNode = new ObjectNode(factory); assertTrue(expressionEvaluatorMock.isNodeEmpty(objectNode)); objectNode.set("empty array", new ArrayNode(factory)); assertTrue(expressionEvaluatorMock.isNodeEmpty(objectNode)); objectNode.set("key", new TextNode("value")); assertFalse(expressionEvaluatorMock.isNodeEmpty(objectNode)); ArrayNode arrayNode = new ArrayNode(factory); assertTrue(expressionEvaluatorMock.isNodeEmpty(arrayNode)); arrayNode.add(new TextNode("value")); assertFalse(expressionEvaluatorMock.isNodeEmpty(arrayNode)); assertTrue(expressionEvaluatorMock.isNodeEmpty(new TextNode(""))); assertTrue(expressionEvaluatorMock.isNodeEmpty(new TextNode(null))); assertFalse(expressionEvaluatorMock.isNodeEmpty(new TextNode("value"))); }
Source:
<code>public Response toResponse(SearchChargesException exception) { <START> PaymentError paymentError = null; <END> if (exception.getErrorStatus() == NOT_FOUND.getStatusCode()) { return buildResponse(exception, SEARCH_PAYMENTS_NOT_FOUND, NOT_FOUND); } return buildResponse(exception, SEARCH_PAYMENTS_CONNECTOR_ERROR, INTERNAL_SERVER_ERROR); }</code><technical_language>paymentError is</technical_language>

Target:
public Response toResponse(SearchChargesException exception) { if (exception.getErrorStatus() == NOT_FOUND.getStatusCode()) { return buildResponse(exception, SEARCH_PAYMENTS_NOT_FOUND, NOT_FOUND); } return buildResponse(exception, SEARCH_PAYMENTS_CONNECTOR_ERROR, INTERNAL_SERVER_ERROR); }