auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void processAttributeSet(String msg, MessageBeans beans) { if(beans.getAttribute() == null || beans.getUser() == null) { return; } try { log.debug("Setting attribute for user {}", beans.getAttribute(), beans.getUser()); if (beans.getAttribute().getNamespace().contains(":virt")) { <START> perunUser.modifyEntry(beans.getUser(), ldapcManager.getPerunBl().getAttributesManager(). <END> getAttribute(ldapcManager.getPerunSession(), beans.getUser(), beans.getAttribute().getName())); } else { perunUser.modifyEntry(beans.getUser(), beans.getAttribute()); } } catch (PerunException e) { log.error("Error setting attribute for user {}: {}", beans.getAttribute().getId(), beans.getUser().getId(), e); } }</code><technical_language>AttributesManagerBl casting returned object ldapcManager.getPerunBl() Perun PerunBl</technical_language>

Target:
public void processAttributeSet(String msg, MessageBeans beans) { if (beans.getAttribute() == null || beans.getUser() == null) { return; } try { log.debug("Setting attribute for user {}", beans.getAttribute(), beans.getUser()); perunUser.modifyEntry(beans.getUser(), beans.getAttribute()); } catch (NamingException | InternalErrorException e) { log.error("Error setting attribute for user {}: {}", beans.getAttribute().getId(), beans.getUser().getId(), e); } }
Source:
<code>public static FileSystem getFileSystem() throws IOException { String coreSitePath = "/usr/local/hadoop/conf/core-site.xml"; Configuration configuration = new Configuration(); configuration.addResource(new Path(coreSitePath)); <START> FileSystem fs = FileSystem.get(configuration); <END> return fs; }</code><technical_language>return FileSystem.get(configuration);</technical_language>

Target:
public static FileSystem getFileSystem() throws IOException { String coreSitePath = "/usr/local/hadoop/conf/core-site.xml"; Configuration configuration = new Configuration(); configuration.addResource(new Path(coreSitePath)); return FileSystem.get(configuration); }
Source:
<code><R extends Row,T> ListenableFuture<Object> issueRowRequest( final Row row, final Batch.Callback<T> callback, final Object[] results, final int index) { LOG.trace("issueRowRequest(Row, Batch.Callback, Object[], index"); SettableFuture<Object> resultFuture = SettableFuture.create(); results[index] = null; ListenableFuture<? extends GeneratedMessage> future = issueRequest(row); <START> if (future != null) { <END> Futures.addCallback(future, new RpcResultFutureCallback<T, GeneratedMessage>( row, callback, index, results, resultFuture) { @Override Object adaptResponse(GeneratedMessage response) { if (response instanceof com.google.bigtable.v1.Row) { return rowToResultAdapter.adaptResponse((com.google.bigtable.v1.Row) response); } else { return new Result(); } } }, service); } else { resultFuture.setException(new UnsupportedOperationException( String.format("Unknown action type %s", row.getClass().getCanonicalName()))); } return resultFuture; }</code><technical_language>issueRequest return null</technical_language>

Target:
<R extends Row,T> ListenableFuture<Object> issueRowRequest( final Row row, final Batch.Callback<T> callback, final Object[] results, final int index) { LOG.trace("issueRowRequest(Row, Batch.Callback, Object[], index"); SettableFuture<Object> resultFuture = SettableFuture.create(); results[index] = null; ListenableFuture<? extends GeneratedMessage> future = issueRequest(row); Futures.addCallback(future, new RpcResultFutureCallback<T, GeneratedMessage>( row, callback, index, results, resultFuture, rowResultConverter), service); return resultFuture; }
Source:
<code>public void shouldPurgeAnAutoGenerationOption() throws Exception { <START> assertNotNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); <END> MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(Integer.parseInt(getUuid()))); }</code><technical_language>do need call Integer.parseInt(getUuid()) more in a method</technical_language>

Target:
public void shouldPurgeAnAutoGenerationOption() throws Exception { assertNotNull(identifierSourceService.getAutoGenerationOption(getId())); MockHttpServletRequest req = request(RequestMethod.DELETE, getURI() + "/" + getUuid()); req.addParameter("purge", ""); handle(req); assertNull(identifierSourceService.getAutoGenerationOption(getId())); }
Source:
<code>public Subject authenticate(Object credentials) { String username; Properties credProps = new Properties(); if (credentials instanceof String[]) { final String[] aCredentials = (String[]) credentials; username = aCredentials[0]; credProps.setProperty(ResourceConstants.USER_NAME, aCredentials[0]); credProps.setProperty(ResourceConstants.PASSWORD, aCredentials[1]); } else if (credentials instanceof String) { <START> username = ""; <END> credProps.setProperty(ResourceConstants.TOKEN, (String) credentials); } else { throw new AuthenticationFailedException(MISSING_CREDENTIALS_MESSAGE); } org.apache.shiro.subject.Subject shiroSubject = this.securityService.login(credProps); Principal principal; if (shiroSubject == null) { principal = new JMXPrincipal(username); } else { principal = new ShiroPrincipal(shiroSubject); } return new Subject(true, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet()); }</code><technical_language>this is good. a unique string based token nice</technical_language>

Target:
public Subject authenticate(Object credentials) { String username; Properties credProps = new Properties(); if (credentials instanceof String[]) { final String[] aCredentials = (String[]) credentials; username = aCredentials[0]; credProps.setProperty(ResourceConstants.USER_NAME, aCredentials[0]); credProps.setProperty(ResourceConstants.PASSWORD, aCredentials[1]); } else if (credentials instanceof String) { username = "token-" + credentials.hashCode(); credProps.setProperty(ResourceConstants.TOKEN, (String) credentials); } else { throw new AuthenticationFailedException(MISSING_CREDENTIALS_MESSAGE); } org.apache.shiro.subject.Subject shiroSubject = this.securityService.login(credProps); Principal principal; if (shiroSubject == null) { principal = new JMXPrincipal(username); } else { principal = new ShiroPrincipal(shiroSubject); } return new Subject(true, Collections.singleton(principal), Collections.emptySet(), Collections.emptySet()); }
Source:
<code>public void createClient() { <START> config.setCapabilities(List.of(KieServerConstants.CAPABILITY_BPM_UI)); <END> uiClient = KieServicesFactory.newKieServicesClient(config).getServicesClient(UIServicesClient.class); }</code><technical_language>code needs compatible Java 8. List.of() brought in Java 9. please refactor code Java 8 compatible</technical_language>

Target:
public void createClient() { config.setCapabilities(Arrays.asList(KieServerConstants.CAPABILITY_BPM_UI)); uiClient = KieServicesFactory.newKieServicesClient(config).getServicesClient(UIServicesClient.class); }
Source:
<code>public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new SetViewportToSizeOf(READONLY_GBUFFER, displayResolutionDependentFBOs)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); update(); <START> displayResolutionDependentFBOs.subscribe(this); <END> }</code><technical_language>move this please</technical_language>

Target:
public void initialise() { wireframeStateChange = new SetWireframe(true); renderingDebugConfig = config.getRendering().getDebug(); new WireframeTrigger(renderingDebugConfig, this); playerCamera = worldRenderer.getActiveCamera(); addDesiredStateChange(new LookThrough(playerCamera)); addDesiredStateChange(new BindFBO(READONLY_GBUFFER, displayResolutionDependentFBOs)); }
Source:
<code>public Optional<Boolean> match(String principal, String user) { Matcher matcher = principalRegex.matcher(principal); if (matcher.matches()) { if (userRegex.isPresent()) { String userPattern = matcher.replaceAll(userRegex.get()); if (Pattern.compile(userPattern).matcher(user).matches()) { <START> return Optional.of(allow); <END> } } else { for (int i = 1; i <= matcher.groupCount(); i++) { String extractedUsername = matcher.group(i); if (user.equals(extractedUsername)) { return Optional.of(allow); } } } } return Optional.empty(); }</code><technical_language>s/match/tryMatch</technical_language>

Target:
public Optional<Boolean> match(String principal, String user) { Matcher matcher = principalRegex.matcher(principal); if (!matcher.matches()) { return Optional.empty(); } if (userRegex.isPresent()) { if (userRegex.get().matcher(user).matches()) { return Optional.of(allow); } } if (principalToUserSubstitution.isPresent()) { String userExtraction = matcher.replaceAll(principalToUserSubstitution.get()); if (user.equals(userExtraction)) { return Optional.of(allow); } } return Optional.empty(); }
Source:
<code>public Map<String, RowMetaInterface> getInputFields( StreamLookupMeta meta ) { Map<String, RowMetaInterface> rowMeta = super.getInputFields( meta ); if ( parentTransMeta != null ) { for ( String prevStepName : parentTransMeta.getStepNames() ) { if ( !rowMeta.containsKey( prevStepName ) ) { try { rowMeta.put( prevStepName, parentTransMeta.getPrevStepFields( prevStepName ) ); } catch ( KettleStepException e ) { <START> LOGGER.warn( Messages.getString( "WARNING.CannotDetermineRowMeta" ) ); <END> } } } } return rowMeta; }</code><technical_language>message wants parameters, passed in</technical_language>

Target:
public Map<String, RowMetaInterface> getInputFields( StreamLookupMeta meta ) { Map<String, RowMetaInterface> rowMeta = super.getInputFields( meta ); if ( parentTransMeta != null ) { for ( String prevStepName : parentTransMeta.getStepNames() ) { if ( !rowMeta.containsKey( prevStepName ) ) { try { rowMeta.put( prevStepName, parentTransMeta.getPrevStepFields( prevStepName ) ); } catch ( KettleStepException e ) { LOGGER.warn( Messages.getString( "WARNING.CannotDetermineRowMeta", prevStepName, e.getLocalizedMessage() ) ); } } } } return rowMeta; }
Source:
<code>void recoveredCommittables(List<GlobalCommT> committables) { <START> this.currentGlobalCommittables = globalCommitter.filterRecoveredCommittables(committables); <END> }</code><technical_language>Remove this. if needed in constructor</technical_language>

Target:
void recoveredCommittables(List<GlobalCommT> committables) { final List<GlobalCommT> recovered = globalCommitter. filterRecoveredCommittables(checkNotNull(committables)); recoveredGlobalCommittables.addAll(recovered); }
Source:
<code>public void addWatcher(Project project, User watcher) { watchManager.watch(project, watcher); <START> currentSession().update(project); <END> }</code><technical_language>a fix in a PR [removes watchManager](<LINK_0>, get squashed this :)</technical_language>

Target:
public void addWatcher(Project project, User watcher) { log.debug("Adding watcher " + watcher.getLoginName() + " to " + project.getName() + " via WatchManager"); project.addWatcher(watcher); currentSession().update(project); }
Source:
<code>public static long parseDuration(String durationStr) { Preconditions.checkArgument(!Strings.isNullOrEmpty(durationStr)); durationStr = durationStr.trim().toLowerCase(); String value = durationStr.substring(0, durationStr.length() - 1); long parsedValue; try { parsedValue = Long.parseLong(value); } catch (NumberFormatException e) { throw new IllegalArgumentException( <START> String.format("Error parsing the duration string %s. Cannot parse string %s to its long value", <END> durationStr, value)); } char lastChar = durationStr.charAt(durationStr.length() - 1); switch (lastChar) { case 's': return TimeUnit.SECONDS.toMillis(parsedValue); case 'm': return TimeUnit.MINUTES.toMillis(parsedValue); case 'h': return TimeUnit.HOURS.toMillis(parsedValue); case 'd': return TimeUnit.DAYS.toMillis(parsedValue); } throw new IllegalArgumentException(String.format("Time unit not supported: %s", lastChar)); }</code><technical_language>parse %s a long</technical_language>

Target:
public static long parseDuration(String durationStr) { Preconditions.checkArgument(!Strings.isNullOrEmpty(durationStr)); durationStr = durationStr.trim().toLowerCase(); String value = durationStr.substring(0, durationStr.length() - 1); long parsedValue; try { parsedValue = Long.parseLong(value); } catch (NumberFormatException e) { throw new IllegalArgumentException( String.format("Error parsing the duration string %s. Cannot parse %s as a long", durationStr, value)); } char lastChar = durationStr.charAt(durationStr.length() - 1); switch (lastChar) { case 's': return TimeUnit.SECONDS.toMillis(parsedValue); case 'm': return TimeUnit.MINUTES.toMillis(parsedValue); case 'h': return TimeUnit.HOURS.toMillis(parsedValue); case 'd': return TimeUnit.DAYS.toMillis(parsedValue); } throw new IllegalArgumentException(String.format("Time unit not supported: %s", lastChar)); }
Source:
<code>public int[] getYearsForJournal(Site site) throws IOException, ParseException { Map<String, String> rawQueryParams = new HashMap(); rawQueryParams.put("stats", "true"); <START> rawQueryParams.put("stats.field", "publication_date"); <END> Map<String, Map> rawResult = (Map<String, Map>) solrSearchService.simpleSearch("", site, 0, 0, SolrSearchService.SolrSortOrder .RELEVANCE, SolrSearchService.SolrDateRange.ALL_TIME,rawQueryParams); Map<String, Map> statsField = (Map<String, Map>) rawResult.get("stats").get("stats_fields"); Map<String, String> publicationDate = (Map<String, String>) statsField.get("publication_date"); SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); Calendar date = Calendar.getInstance(); date.setTime(dateFormat.parse(publicationDate.get("min"))); int minYear = date.get(Calendar.YEAR); date.setTime(dateFormat.parse(publicationDate.get("max"))); int maxYear = date.get(Calendar.YEAR); int[] yearRange = {minYear, maxYear}; return yearRange; }</code><technical_language>I of this direct manipulation of solr fields this class violates separation of concerns enforce SolrSearchService. SolrSearchService class solr details (with exception of templates, deal in deserialized json returned solr). I of approaches: move this entire method SolrSearchService. Or, this method a thin wrapper a SolrSearchService method (maybe call listArticles, a search), this method responsible for pulling out years SearchService results. approach violates separation of concerns a bit, bad was. I advantages disadvantages approaches, leave decision you</technical_language>

Target:
public Map<?, ?> getYearsForJournal(Site site) throws IOException, ParseException { Map<String, String> yearRange = (Map<String, String>) solrSearchService.getStats("publication_date", site); return yearRange; }
Source:
<code>public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); <START> mesosSlaveInfoList = fetchMesosSlaveInfoFromJSON(object); <END> save(); return super.configure(request, object); }</code><technical_language>Is this method more once? If not, lets factor out</technical_language>

Target:
public boolean configure(StaplerRequest request, JSONObject object) throws FormException { nativeLibraryPath = object.getString("nativeLibraryPath"); master = object.getString("master"); description = object.getString("description"); frameworkName = object.getString("frameworkName"); slaveAttributes = object.getString("slaveAttributes"); checkpoint = object.getBoolean("checkpoint"); slaveInfos = new ArrayList<MesosSlaveInfo>(); JSONArray labels = object.getJSONArray("slaveInfos"); if (labels != null) { for (int i = 0; i < labels.size(); i++) { JSONObject label = labels.getJSONObject(i); if (label != null) { MesosSlaveInfo slaveInfo = new MesosSlaveInfo( object.getString("labelString"), object.getString("slaveCpus"), object.getString("slaveMem"), object.getString("maxExecutors"), object.getString("executorCpus"), object.getString("executorMem"), object.getString("idleTerminationMinutes"), object.getString("slaveAttributes")); slaveInfos.add(slaveInfo); } } } save(); return super.configure(request, object); }
Source:
<code>public int hashCode() { <START> int hash = 7; <END> hash = 31 * hash + Objects.hashCode(id); hash = 31 * hash + Objects.hashCode(email); hash = 31 * hash + getAttributes().hashCode(); return hash; }</code><technical_language>java.util.Objects.hash(id, email, getAttributes())</technical_language>

Target:
public int hashCode() { int hash = 7; hash = 31 * hash + Objects.hashCode(id); hash = 31 * hash + getAttributes().hashCode(); return hash; }
Source:
<code>private int createHashCode() { int result = annotationDescriptor.hashCode(); result = 31 * result + validatedType.hashCode(); result = 31 * result + constraintValidatorFactory.hashCode(); result = 31 * result + scriptEvaluatorFactory.hashCode(); result = 31 * result + clockProvider.hashCode(); <START> result = 31 * result + temporalValidationTolerance.hashCode(); <END> return result; }</code><technical_language>idea equals() hashCode() defined for initialization context. expose isolated. hashCode in context created in constructor cached (we a createHashCode() pattern in places of code)</technical_language>

Target:
private int createHashCode() { int result = annotationDescriptor.hashCode(); result = 31 * result + validatedType.hashCode(); result = 31 * result + constraintValidatorFactory.hashCode(); result = 31 * result + constraintValidatorInitializationContext.hashCode(); return result; }
Source:
<code>public PremisLogger getPremisLogger(PID pid) { File file = new File(depositDirectory, DepositConstants.EVENTS_DIR + "/" + pid.getUUID() + ".ttl"); try { PremisLogger premisLogger; if (!file.exists()) { file.getParentFile().mkdirs(); } <START> premisLogger = createNewEventsFile(pid, file); <END> return premisLogger; } catch (IOException e) { failJob(e, "Unexpected problem with deposit events file {}.", file.getAbsoluteFile()); } return null; }</code><technical_language>I drop createNewEventsFile, method is is calling constructor of PremisLogger is actual file creation</technical_language>

Target:
public PremisLogger getPremisLogger(PID pid) { File file = new File(depositDirectory, DepositConstants.EVENTS_DIR + "/" + pid.getUUID() + ".ttl"); try { if (!file.exists()) { file.getParentFile().mkdirs(); } return new PremisLogger(pid, file); } catch (Exception e) { failJob(e, "Unexpected problem with deposit events file {}.", file.getAbsoluteFile()); } return null; }
Source:
<code><START> private Channel createQueues(Connection connection) throws IOException, MalformedURLException, URISyntaxException { <END> Channel channel; channel = connection.createChannel(); for (String queueName : this.queues) { if (this.purge) { logger.debug("Deleting queue: " + queueName); channel.queueDelete(queueName); } if (isDefaultQueue(queueName)) { channel.queueDelete(queueName); } else { channel.queueDeclare(queueName, true, false, false, null); } } brokerOffline.put(this.port, false); if (!this.assumeOnline) { Assume.assumeTrue(brokerOffline.get(this.port)); } if (this.management) { Client client = new Client(getAdminUri(), this.adminUser, this.adminPassword); if (!client.alivenessTest("/")) { throw new BrokerNotAliveException("Aliveness test failed for localhost:15672 guest/quest; " + "management not available"); } } return channel; }</code><technical_language>A MalformedURLException is redundant</technical_language>

Target:
private Channel createQueues(Connection connection) throws IOException, URISyntaxException { Channel channel; channel = connection.createChannel(); for (String queueName : this.queues) { if (this.purge) { LOGGER.debug("Deleting queue: " + queueName); channel.queueDelete(queueName); } if (isDefaultQueue(queueName)) { channel.queueDelete(queueName); } else { channel.queueDeclare(queueName, true, false, false, null); } } BROKER_OFFLINE.put(this.port, false); if (!this.assumeOnline) { Assume.assumeTrue(BROKER_OFFLINE.get(this.port)); } if (this.management) { Client client = new Client(getAdminUri(), this.adminUser, this.adminPassword); if (!client.alivenessTest("/")) { throw new BrokerNotAliveException("Aliveness test failed for localhost:15672 guest/quest; " + "management not available"); } } return channel; }
Source:
<code>public boolean hasPrimaryTerm() { <START> return this.primaryTerm != null && SequenceNumbers.isAssignedPrimaryTerm(this.primaryTerm); <END> }</code><technical_language>suggestion return this.primaryTerm != null;</technical_language>

Target:
public boolean hasPrimaryTerm() { return this.primaryTerm != null; }
Source:
<code>public ActionExecutionException toActionExecutionException( String messagePrefix, boolean verboseFailures, Action action) { if (messagePrefix == null) { messagePrefix = action.describe(); } String message = result.getDetailMessage(messagePrefix, getMessage(), isCatastrophic(), forciblyRunRemotely); if (verboseFailures) { <START> return new ActionExecutionException(message + ": " + getMessage(), this, action, isCatastrophic(), getExitCode()); <END> } else { return new ActionExecutionException(message, action, isCatastrophic(), getExitCode()); } }</code><technical_language>code I follow this fixes it. of getMessage() is appended message implementation of SpawnResult#getDetailMessage. appending help</technical_language>

Target:
public ActionExecutionException toActionExecutionException( String messagePrefix, boolean verboseFailures, Action action) { if (messagePrefix == null) { messagePrefix = action.describe(); } String message = result.getDetailMessage(messagePrefix, getMessage(), verboseFailures, isCatastrophic(), forciblyRunRemotely); return new ActionExecutionException(message, this, action, isCatastrophic(), getExitCode()); }
Source:
<code>private List<String> buildExpectedErrorMessages() { String feedbackSessionNameError = "The field 'feedback session name' is empty. The value of a/an feedback " + "session name should be no longer than 38 characters. It should not be empty."; String courseIdError = "The field 'course ID' is empty. A course ID can contain letters, numbers, fullstops, " + "hyphens, underscores, and dollar signs. It cannot be longer than 40 characters, cannot be empty and " + "cannot contain spaces."; String creatorEmailError = "The field 'email' is empty. An email address contains some text followed " + "by one '@' sign followed by some more text. It cannot be longer than 254 characters, cannot be empty" + " and cannot contain spaces."; String gracePeriodError = "Grace period should never be negative."; <START> return Arrays.asList(feedbackSessionNameError, courseIdError, creatorEmailError, gracePeriodError); <END> }</code><technical_language>revert this removal of a blank line unrelated change</technical_language>

Target:
private List<String> buildExpectedErrorMessages() { String feedbackSessionNameError = "The field 'feedback session name' is empty. The value of a/an feedback " + "session name should be no longer than 38 characters. It should not be empty."; String courseIdError = "The field 'course ID' is empty. A course ID can contain letters, numbers, fullstops, " + "hyphens, underscores, and dollar signs. It cannot be longer than 40 characters, cannot be empty and " + "cannot contain spaces."; String creatorEmailError = "The field 'email' is empty. An email address contains some text followed " + "by one '@' sign followed by some more text. It cannot be longer than 254 characters, cannot be empty" + " and cannot contain spaces."; String gracePeriodError = "Grace period should not be negative." + " " + "The value must be one of the options in the grace period dropdown selector."; return Arrays.asList(feedbackSessionNameError, courseIdError, creatorEmailError, gracePeriodError); }
Source:
<code>public Future<Long> write(ByteBuffer src, Callback<Long> callback) { <START> if (src == null) { <END> throw new IllegalArgumentException("Source buffer cannot be null"); } ChunkData chunkData = new ChunkData(Unpooled.wrappedBuffer(src), callback); chunks.add(chunkData); if (channelEventListener != null) { channelEventListener.onEvent(EventType.Write); } if (!isOpen()) { resolveAllRemainingChunks(new ClosedChannelException()); } return chunkData.future; }</code><technical_language>replace this impl a call write(Unpooled.wrappedBuffer(src), callback)</technical_language>

Target:
public Future<Long> write(ByteBuffer src, Callback<Long> callback) { if (src == null) { throw new IllegalArgumentException("Source buffer cannot be null"); } return write(Unpooled.wrappedBuffer(src), callback); }
Source:
<code>private DirectEditManager getManager() { if <START> (manager == null) { <END> manager = createDirectEditManager(); } return manager; }</code><technical_language>null == manager</technical_language>

Target:
private DirectEditManager getManager() { if (null == manager) { manager = createDirectEditManager(); } return manager; }
Source:
<code>public void startServer() throws RemotingException { <START> port = (int) (1000 * Math.random() + 10000); <END> ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Object.class, (channel, msg) -> { for (int i = 0; i < 10000; i++) { System.currentTimeMillis(); } System.out.println("handle:" + msg + ";thread:" + Thread.currentThread().getName()); return new StringMessage("hello world"); }); exchangeServer = Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); }</code><technical_language>if for a random port (which is available), check NetUtils.getAvailablePort()</technical_language>

Target:
public void startServer() throws RemotingException { port = NetUtils.getAvailablePort(); ReplierDispatcher dispatcher = new ReplierDispatcher(); dispatcher.addReplier(RpcMessage.class, new RpcMessageHandler()); dispatcher.addReplier(Object.class, (channel, msg) -> { for (int i = 0; i < 10000; i++) { System.currentTimeMillis(); } return new StringMessage("hello world"); }); exchangeServer = Exchangers.bind(URL.valueOf("dubbo://localhost:" + port), dispatcher); }
Source:
<code>public List<String> listFiles(PluginTask task) { AmazonS3Client client = newS3Client(task); String bucketName = task.getBucket(); ImmutableList.Builder<String> builder = ImmutableList.builder(); for (String prefix : task.getPathPrefixes()) { try { builder.addAll(listS3FilesByPrefix(client, bucketName, formatPrefix(prefix))); } catch (Exception e) { <START> log.warn("Cannot parse prefix: "+prefix, e); <END> } } return builder.build(); }</code><technical_language>This catches exceptions. 1. I exceptions formatPath a fatal error. Users notice path includes invalid syntax. 2. If listS3FilesByPrefix throws exception, fatal. result invalid</technical_language>

Target:
public List<String> listFiles(PluginTask task) { AmazonS3Client client = newS3Client(task); String bucketName = task.getBucket(); ImmutableList.Builder<String> builder = ImmutableList.builder(); for (String prefix : task.getPathPrefixes()) { String formatted; try { formatted = formatPrefix(prefix); } catch (RuntimeException e) { log.error("Cannot parse the invalid prefix. An invalid syntax is included in: "+prefix); throw e; } try { builder.addAll(listS3FilesByPrefix(client, bucketName, formatted)); } catch (RuntimeException e) { String message; String errMessage = e.getMessage(); if (e instanceof AmazonServiceException) { message = "an error occurred in Amazon S3: "+errMessage; } else if (e instanceof AmazonClientException) { message = "an error was encountered in the client: "+errMessage; } else { message = "Cannot get a list of the objects: "+prefix+": "+e.getMessage(); } log.error(message); throw e; } } return builder.build(); }
Source:
<code>private static int getSystemPropertyAndParseInt(String key, int defaultValue) { try { return Integer.parseInt(System.getProperty(key)); } catch (NumberFormatException e) { StatusHandler.log(new Status(IStatus.WARNING, CommonsCorePlugin.ID_PLUGIN, NLS.bind( "Unable to parse property {0}", key))); <START> System.setProperty(key, Integer.toString(defaultValue)); <END> } return defaultValue; }</code><technical_language>log a warning, happen. if prop is set, I this way</technical_language>

Target:
private static int getSystemPropertyAndParseInt(String key, int defaultValue) { String property = System.getProperty(key); if (property != null) { try { return Integer.parseInt(property); } catch (NumberFormatException e) { StatusHandler.log(new Status(IStatus.WARNING, CommonsCorePlugin.ID_PLUGIN, NLS.bind( "Unable to parse property {0}", key))); } } return defaultValue; }
Source:
<code>public String toString() { StringBuilder builder = new StringBuilder(); <START> for (String segment : fInput) { <END> builder.append(segment).append(' '); } return nullToEmptyString(builder.toString().trim()); }</code><technical_language>Re-entrancy is important for this class, fInput modified while this method is running, give weird results. easy fix getInput() instead of 'fInput'</technical_language>

Target:
public String toString() { StringBuilder builder = new StringBuilder(); for (String segment : getInput()) { builder.append(segment).append(' '); } return nullToEmptyString(builder.toString().trim()); }
Source:
<code>public void testGetZeroContents() throws IOException { final FileSystemManager fsManager = VFS.getManager(); <START> final FileObject fo = fsManager.resolveFile("http4://monpremierlivre.home.blog/"); <END> final FileContent content = fo.getContent(); Assert.assertNotNull(content.getString(StandardCharsets.UTF_8)); }</code><technical_language>I want Mockito instead of depending a random party web site -- random Apache's POV ;-)</technical_language>

Target:
public void testGetZeroContents() throws IOException { final FileSystemManager fsManager = VFS.getManager(); final FileObject fo = fsManager.resolveFile("http4s://www.apache.org/dist/"); final FileContent content = fo.getContent(); Assert.assertEquals(0L, content.getSize()); Assert.assertNotNull(content.getString(StandardCharsets.UTF_8)); }
Source:
<code>public TableDefinitionRepositoryKey(String name, Optional<String> schema) { <START> this.name = name; <END> this.schema = schema; }</code><technical_language>requireNonNull</technical_language>

Target:
public TableDefinitionRepositoryKey(String name, Optional<String> schema) { this.name = requireNonNull(name, "name is null"); this.schema = requireNonNull(schema, "schema is null"); }
Source:
<code>void addStudyVariablesToUnitRows(final List<ObservationUnitRow> observationUnits, final List<MeasurementVariable> studyVariables) { for (final ObservationUnitRow observationUnitRow : observationUnits) { for (final MeasurementVariable measurementVariable : studyVariables) { final String key; <START> if (measurementVariable.getAlias() != null && !measurementVariable.getAlias().equals("")) { <END> key = measurementVariable.getAlias(); } else { key = measurementVariable.getName(); } observationUnitRow.getVariables() .put(key, new ObservationUnitData(measurementVariable.getValue())); } } }</code><technical_language>StringUtils.isEmpty</technical_language>

Target:
void addStudyVariablesToUnitRows(final List<ObservationUnitRow> observationUnits, final List<MeasurementVariable> studyVariables) { for (final ObservationUnitRow observationUnitRow : observationUnits) { for (final MeasurementVariable measurementVariable : studyVariables) { final String key; if (!StringUtils.isEmpty(measurementVariable.getAlias())) { key = measurementVariable.getAlias(); } else { key = measurementVariable.getName(); } observationUnitRow.getVariables() .put(key, new ObservationUnitData(measurementVariable.getValue())); } } }
Source:
<code>public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters) throws Exception { Preconditions.checkArgument(parameters.containsKey(IMPORT_DATABASE_SERVICE_DBNAME), "unknown database holding projects name, required parameter '%s' is missing!", IMPORT_DATABASE_SERVICE_DBNAME); FileSystem fs = FileSystem.get(conf); try (DataFileWriter<Project> projectWriter = DataStore.create( new FileSystemPath(fs, portBindings.getOutput().get(PORT_OUT_PROJECT)), Project.SCHEMA$)) { DatabaseFacade databaseFacade = ServiceFacadeUtils.instantiate(parameters); StringWriter writer = new StringWriter(); <START> IOUtils.copy(this.getClass().getClassLoader().getResourceAsStream(queryLocation), writer, "utf-8"); <END> SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = parserFactory.newSAXParser(); int currentCount = 0; long startTime = System.currentTimeMillis(); for (String record : databaseFacade.searchSQL(parameters.get(IMPORT_DATABASE_SERVICE_DBNAME), writer.toString())) { saxParser.parse(new InputSource(new StringReader(record)), new DatabaseProjectXmlHandler(new DataFileRecordReceiver<Project>(projectWriter))); currentCount++; if (currentCount%progressLogInterval==0) { log.debug("current progress: " + currentCount + ", last package of " + progressLogInterval + " processed in " + ((System.currentTimeMillis()-startTime)/1000) + " secs"); startTime = System.currentTimeMillis(); } } } }</code><technical_language>I move reading this sql private method returning a string. in this method wrap writer in try block (it's a good convention close opened writers - if do closing)</technical_language>

Target:
public void run(PortBindings portBindings, Configuration conf, Map<String, String> parameters) throws Exception { Preconditions.checkArgument(parameters.containsKey(IMPORT_DATABASE_SERVICE_DBNAME), "unknown database holding projects name, required parameter '%s' is missing!", IMPORT_DATABASE_SERVICE_DBNAME); FileSystem fs = FileSystem.get(conf); try (DataFileWriter<Project> projectWriter = DataStore.create( new FileSystemPath(fs, portBindings.getOutput().get(PORT_OUT_PROJECT)), Project.SCHEMA$)) { DatabaseFacade databaseFacade = ServiceFacadeUtils.instantiate(parameters); SAXParserFactory parserFactory = SAXParserFactory.newInstance(); SAXParser saxParser = parserFactory.newSAXParser(); int currentCount = 0; long startTime = System.currentTimeMillis(); for (String record : databaseFacade.searchSQL(parameters.get(IMPORT_DATABASE_SERVICE_DBNAME), loadQuery())) { saxParser.parse(new InputSource(new StringReader(record)), new DatabaseProjectXmlHandler(new DataFileRecordReceiver<Project>(projectWriter))); currentCount++; if (currentCount%progressLogInterval==0) { log.debug("current progress: " + currentCount + ", last package of " + progressLogInterval + " processed in " + ((System.currentTimeMillis()-startTime)/1000) + " secs"); startTime = System.currentTimeMillis(); } } } }
Source:
<code>public void slicesOfOneFromOne() { <START> Series series = new Series("1"); <END> List<List<Integer>> expected = Arrays.asList(Collections.singletonList(1)); List<Integer> actual = series.slice(1); assertNotNull(actual); assertFalse(actual.isEmpty()); assertEquals(expected, actual); }</code><technical_language>indentation appears a bit wrong in this file. Please is indented correctly, spaces for indentation</technical_language>

Target:
public void slicesOfOneFromOne() { Series series = new Series("1"); List<List<String>> expected = Arrays.asList(Arrays.asList("1")); List<List<String>> actual = series.slices(1); assertEquals(expected, actual); }
Source:
<code>public boolean cancelOrder(String orderId) throws IOException { CoingiCancelOrderRequest request = new CoingiCancelOrderRequest(); request.setOrderId(orderId); CoingiOrder order; try { <START> order = cancelCoingiOrder(request); <END> } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } return order != null; }</code><technical_language>try / catch CoingiException hit applied</technical_language>

Target:
public boolean cancelOrder(String orderId) throws IOException { try { CoingiCancelOrderRequest request = new CoingiCancelOrderRequest(); request.setOrderId(orderId); return cancelCoingiOrder(request) != null; } catch (CoingiException e) { throw CoingiErrorAdapter.adapt(e); } }
Source:
<code>@Override protected void beforeTestsStarted() throws Exception { <START> System.setProperty(IGNITE_BASELINE_AUTO_ADJUST_ENABLED, "false"); U.resolveWorkDirectory(U.defaultWorkDirectory(), "db", true); <END> super.beforeTestsStarted(); grid(0).cluster().active(true); }</code><technical_language>do need lines</technical_language>

Target:
@Override protected void beforeTestsStarted() throws Exception { super.beforeTestsStarted(); grid(0).cluster().active(true); }
Source:
<code>public void setUp() throws Exception { provisioner = new LocalCheDockerEnvironmentProvisioner( false, settingsProvisioners, projectsVolumeProvisioner, installerConfigProvisioner, labelsProvisioner, dockerApiEnvProvisioner, wsAgentServerConfigProvisioner, <START> singlePortLabelsProvisioner, <END> serversConverter, envVarsConverter, memoryAttributeConverter, volumesConverter); allInnerProvisioners = new Object[] { settingsProvisioners, projectsVolumeProvisioner, installerConfigProvisioner, labelsProvisioner, dockerApiEnvProvisioner, wsAgentServerConfigProvisioner, serversConverter, envVarsConverter, memoryAttributeConverter, volumesConverter }; }</code><technical_language>single port labels provisioning is covered in this test</technical_language>

Target:
public void setUp() throws Exception { provisioner = new LocalCheDockerEnvironmentProvisioner( true, settingsProvisioners, projectsVolumeProvisioner, installerConfigProvisioner, labelsProvisioner, dockerApiEnvProvisioner, wsAgentServerConfigProvisioner, singlePortLabelsProvisioner, serversConverter, envVarsConverter, memoryAttributeConverter, volumesConverter); allInnerProvisioners = new Object[] { settingsProvisioners, projectsVolumeProvisioner, installerConfigProvisioner, labelsProvisioner, dockerApiEnvProvisioner, wsAgentServerConfigProvisioner, serversConverter, envVarsConverter, memoryAttributeConverter, volumesConverter, singlePortLabelsProvisioner }; }
Source:
<code>public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } final Device device = (Device) o; if (this.deviceIdentification != null ? !this.deviceIdentification.equals(device.deviceIdentification) : device.deviceIdentification != null) { return false; <START> } <END> return true; }</code><technical_language>I this works equals work, a if prefer shorter: return Objects.equals(this.deviceIdentification, device.deviceIdentification); null checking if result is false, returning true</technical_language>

Target:
public boolean equals(final Object o) { if (this == o) { return true; } if (o == null || this.getClass() != o.getClass()) { return false; } final Device device = (Device) o; return Objects.equals(this.deviceIdentification, device.deviceIdentification); }
Source:
<code>public OrmException convertError(String op, String entity, SQLException err) { switch (err.getErrorCode()) { <START> case 1062: <END> return new OrmDuplicateKeyException(entity, err); default: return fallbackConvertError(op, entity, err); } }</code><technical_language>a constant defined for this</technical_language>

Target:
public OrmException convertError(String op, String entity, SQLException err) { switch (err.getErrorCode()) { case MysqlErrorNumbers.ER_DUP_ENTRY: return new OrmDuplicateKeyException(entity, err); default: return fallbackConvertError(op, entity, err); } }
Source:
<code>public void run() { try { if (build instanceof MatrixBuild) { List<MatrixRun> runs = ((MatrixBuild)build).getRuns(); for (AbstractBuild run : runs) { if (run.getActions(FailureCauseBuildAction.class).isEmpty() && run.getActions(FailureCauseMatrixBuildAction.class).isEmpty() && ResultFilter.needToAnalyze(run.getResult()) && run.getNumber() == build.getNumber()) { scanBuild(run); } } endMatrixBuildScan(); } else { <START> if (ResultFilter.needToAnalyze(build.getResult())) { <END> scanBuild(build); } } } catch (Exception e) { logger.log(Level.WARNING, "Failed to add a FailureScanner to " + build.getProject().getFullDisplayName(), e); } }</code><technical_language>This is for a manual scan concern scan not, user explicitly asked for build scanned be</technical_language>

Target:
public void run() { try { if (build instanceof MatrixBuild) { List<MatrixRun> runs = ((MatrixBuild)build).getRuns(); for (AbstractBuild run : runs) { if (run.getActions(FailureCauseBuildAction.class).isEmpty() && run.getActions(FailureCauseMatrixBuildAction.class).isEmpty() && PluginImpl.needToAnalyze(run.getResult()) && run.getNumber() == build.getNumber()) { scanBuild(run); } } endMatrixBuildScan(); } else { scanBuild(build); } } catch (Exception e) { logger.log(Level.WARNING, "Failed to add a FailureScanner to " + build.getProject().getFullDisplayName(), e); } }
Source:
<code>public void runTetherProvisioningCheck(int type, ResultReceiver receiver) { <START> enforceTetherAccessPermission(); <END> mTethering.runTetherProvisioningCheck(type, receiver); }</code><technical_language>I realized this checks ACCESS_NETWORK_STATE. I appropriate, because: 1. Starting tethering is a privileged information (regular apps do all), point allowing app call this method if do tethering anyway. 2. If provisioning check brings cell data, mobile data traffic a time app able traffic. 3. API guidelines require @SystemApi methods guarded permissions regular apps have. Is a reason this enforceTetherChangePermission</technical_language>

Target:
public void runTetherProvisioningCheck(int type, ResultReceiver receiver) { enforceTetherChangePermission(); mTethering.runTetherProvisioningCheck(type, receiver); }
Source:
<code>public void testStaticVisibilityFromLambdas() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "16:34: " + getCheckMessage(MSG_KEY, "value"), "48:23: " + getCheckMessage(MSG_KEY, "languageCode"), "57:35: " + getCheckMessage(MSG_KEY, "num1"), "70:35: " + getCheckMessage(MSG_KEY, "num2"), <START> "98:23: " + getCheckMessage(MSG_KEY, "lc1"), <END> }; verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/" + "checkstyle/coding/InputHiddenFieldLambdas.java").getCanonicalPath(), expected); }</code><technical_language>some simple words variable, parameter, instead of cryptic lc1</technical_language>

Target:
public void testStaticVisibilityFromLambdas() throws Exception { final DefaultConfiguration checkConfig = createCheckConfig(HiddenFieldCheck.class); final String[] expected = { "16:34: " + getCheckMessage(MSG_KEY, "value"), "48:31: " + getCheckMessage(MSG_KEY, "languageCode"), "57:35: " + getCheckMessage(MSG_KEY, "number"), "70:35: " + getCheckMessage(MSG_KEY, "id"), "98:33: " + getCheckMessage(MSG_KEY, "note"), "123:57: " + getCheckMessage(MSG_KEY, "stringValue"), "123:78: " + getCheckMessage(MSG_KEY, "intValue"), "134:74: " + getCheckMessage(MSG_KEY, "doubleValue"), "146:51: " + getCheckMessage(MSG_KEY, "firstString"), "146:64: " + getCheckMessage(MSG_KEY, "secondString"), "162:49: " + getCheckMessage(MSG_KEY, "first"), "188:62: " + getCheckMessage(MSG_KEY, "mPi"), "204:27: " + getCheckMessage(MSG_KEY, "justSomeList"), "204:61: " + getCheckMessage(MSG_KEY, "justSomeMap"), "216:55: " + getCheckMessage(MSG_KEY, "someObject"), "224:52: " + getCheckMessage(MSG_KEY, "someObject"), }; verify(checkConfig, new File("src/test/resources-noncompilable/com/puppycrawl/tools/" + "checkstyle/coding/InputHiddenFieldLambdas.java").getCanonicalPath(), expected); }
Source:
<code>public boolean isAlias() { <START> return aliasTarget != null; <END> }</code><technical_language>alias wired , runing,</technical_language>

Target:
public boolean isAlias() { return instance instanceof ComponentAlias; }
Source:
<code>public FilesToRunProvider( NestedSet<Artifact> filesToRun, @Nullable RunfilesSupport runfilesSupport, @Nullable Artifact executable) { if (executable != null) { <START> filesToRun = NestedSetBuilder.fromNestedSet(filesToRun).add(executable).build(); <END> } this.filesToRun = filesToRun; this.runfilesSupport = runfilesSupport; this.executable = executable; }</code><technical_language>This create extra NestedSet instance for call site, importantly, in constructor of FileConfiguredTarget, means extra object for input file, is _probably_ unacceptable overhead. special-casing #fromSingleExecutableArtifact() this overhead is present? other call site is in RuleConfiguredTargetBuilder#build(), prefer putting logic because, well, place logic. In addition a personal preference, more information, notably, ruleContext.getRule().getRuleClassObject().isSkylark(), determine this is a Starlark rule adding binary nested set is necessary. is changing SkylarkRuleConfiguredTargetUtil#addSimpleProviders() -- place control executable filesToBuild fields of RuleConfiguredTargetBuilder is specific Starlark rules, add "executable is forcibly added filesToRun" logic there</technical_language>

Target:
public FilesToRunProvider( NestedSet<Artifact> filesToRun, @Nullable RunfilesSupport runfilesSupport, @Nullable Artifact executable) { this.filesToRun = filesToRun; this.runfilesSupport = runfilesSupport; this.executable = executable; }
Source:
<code>public static void setImage(ComponentContainer container, ImageView view, String picturePath) { <START> GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(view); <END> MediaUtil.MediaSource mediaSource = MediaUtil.determineMediaSource(container.$form(), picturePath); switch (mediaSource) { case ASSET: Drawable drawable = null; try { drawable = MediaUtil.getBitmapDrawable(container.$form(), picturePath); } catch (IOException e) { e.printStackTrace(); } view.setImageDrawable(drawable); break; case REPL_ASSET: String path = MediaUtil.replAssetPath(picturePath); try { Glide.with(container.$context()) .load(Uri.fromFile(new File(path))) .into(imageViewTarget); } catch (Exception e) { Log.e("Image", "Unable to load " + path); } break; default: try { Glide.with(container.$context()) .load(Uri.fromFile(new File(picturePath))) .into(imageViewTarget); } catch (Exception e) { Log.e("Image", "Unable to load " + picturePath); } } if (view.getDrawable() != null) { view.setAdjustViewBounds(true); } view.requestLayout(); }</code><technical_language>I this logic if file format is GIF. Otherwise, puts Glide critical path for image, is I want</technical_language>

Target:
public static void setImage(ComponentContainer container, ImageView view, String picturePath) { if (picturePath.endsWith(".gif") && Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD_MR1) { GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(view); MediaUtil.MediaSource mediaSource = MediaUtil.determineMediaSource(container.$form(), picturePath); switch (mediaSource) { case ASSET: try { InputStream is = container.$form().getAssets().open(picturePath); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buf = new byte[4096]; int read; while ((read = is.read(buf)) > 0) { bos.write(buf, 0, read); } buf = bos.toByteArray(); Glide.with(container.$context()) .load(buf) .into(imageViewTarget); } catch (IOException e) { Log.e("Image", "Unable to load " + picturePath); } break; case REPL_ASSET: String replAssetPath = MediaUtil.replAssetPath(picturePath); try { Glide.with(container.$context()) .load(Uri.fromFile(new File(replAssetPath))) .into(imageViewTarget); } catch (Exception e) { Log.e("Image", "Unable to load " + picturePath); } break; default: try { Glide.with(container.$context()) .load(Uri.fromFile(new File(picturePath))) .into(imageViewTarget); } catch (Exception e) { Log.e("Image", "Unable to load " + picturePath); } } } else { Drawable drawable = null; try { drawable = MediaUtil.getBitmapDrawable(container.$form(), picturePath); } catch (IOException e) { e.printStackTrace(); } view.setImageDrawable(drawable); } if (view.getDrawable() != null) { view.setAdjustViewBounds(true); } view.requestLayout(); }