auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private void invalidate(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); clientsToInvalidate.remove(originatingClientDescriptor); InvalidationHolder invalidationHolder = null; if (stores.get(cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); } LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { <START> LOGGER.debug("SERVER: asking client {}" + clientDescriptorThatHasToInvalidate + " to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); <END> try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }</code><technical_language>logging line mixes concatenation variables</technical_language>

Target:
private void invalidate(ClientDescriptor originatingClientDescriptor, String cacheId, long key) { int invalidationId = invalidationIdGenerator.getAndIncrement(); Set<ClientDescriptor> clientsToInvalidate = Collections.newSetFromMap(new ConcurrentHashMap<ClientDescriptor, Boolean>()); clientsToInvalidate.addAll(storeClientMap.get(cacheId)); clientsToInvalidate.remove(originatingClientDescriptor); InvalidationHolder invalidationHolder = null; if (stores.get(cacheId).getStoreConfiguration().getConsistency() == Consistency.STRONG) { invalidationHolder = new InvalidationHolder(originatingClientDescriptor, clientsToInvalidate, cacheId, key); clientsWaitingForInvalidation.put(invalidationId, invalidationHolder); } LOGGER.debug("SERVER: requesting client(s) invalidation of hash in cache (ID {})", clientsToInvalidate.size(), key, cacheId, invalidationId); for (ClientDescriptor clientDescriptorThatHasToInvalidate : clientsToInvalidate) { LOGGER.debug("SERVER: asking client to invalidate hash from cache (ID {})", clientDescriptorThatHasToInvalidate, key, cacheId, invalidationId); try { clientCommunicator.sendNoResponse(clientDescriptorThatHasToInvalidate, clientInvalidateHash(cacheId, key, invalidationId)); } catch (MessageCodecException mce) { LOGGER.error("Codec error", mce); } } if (invalidationHolder != null && clientsToInvalidate.isEmpty()) { clientInvalidated(invalidationHolder.clientDescriptorWaitingForInvalidation, invalidationId); } }
Source:
<code>public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { boolean shiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); if( shiftHeld ) { ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); ItemStack output = iep.getOutput( stack ); <START> if( output != null && !output.isEmpty() ) <END> { IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel( output ); realModel = realModel.getOverrides().handleItemState( realModel, output, world, entity ); return new ShiftHoldingModelWrapper( realModel ); } } return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState( originalModel, stack, world, entity ); }</code><technical_language>A pattern outputs. crafting system needs lookup inputs, mark craftable etc. null ItemStack.EMPTY a question. condensed output empty for usual reasons of a valid pattern, empty collection a collection of null objects on. Treating ItemEncodedPattern#getOutput() @Nonnull is valid. ItemStack.EMPTY is fine use, break receiving null, means another mod created a pattern, create more issues elsewhere</technical_language>

Target:
public IBakedModel handleItemState( IBakedModel originalModel, ItemStack stack, World world, EntityLivingBase entity ) { boolean shiftHeld = Keyboard.isKeyDown( Keyboard.KEY_LSHIFT ) || Keyboard.isKeyDown( Keyboard.KEY_RSHIFT ); if( shiftHeld ) { ItemEncodedPattern iep = (ItemEncodedPattern) stack.getItem(); ItemStack output = iep.getOutput( stack ); if( !output.isEmpty() ) { IBakedModel realModel = Minecraft.getMinecraft().getRenderItem().getItemModelMesher().getItemModel( output ); realModel = realModel.getOverrides().handleItemState( realModel, output, world, entity ); return new ShiftHoldingModelWrapper( realModel ); } } return ItemEncodedPatternBakedModel.this.baseModel.getOverrides().handleItemState( originalModel, stack, world, entity ); }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getCredentialsNew().equals(userCredentials.getConfirmedCredentialsNew())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (AuthenticationException ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); <START> log.debug(msg, ex); <END> SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }</code><technical_language>Please copy error message exception trace: log.error("Change Password for user '{}' failed: {}", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.debug("Exception", ex);</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered InteractiveChangePasswdServlet"); Credentials userCredentials = null; String redirectUrl; try { log.debug("User is not authenticated extracting credentials from request."); userCredentials = getUserCredentials(request); if (userCredentials == null) { throw new AuthenticationException("Unable to extract user credentials from request"); } if (!userCredentials.getNewCredentials().equals(userCredentials.getConfirmedNewCredentials())) { throw new AuthenticationException("The passwords don't match."); } redirectUrl = changeUserPasswd(request, userCredentials); } catch (AuthenticationException ex) { String msg = String.format("Change Password for user '%s' failed : %s", userCredentials == null ? "" : userCredentials.getUsername() + "@" + userCredentials.getProfile(), ex.getMessage()); log.error(msg); log.debug(msg, ex); SSOUtils.getSsoSession(request).setChangePasswdMessage(msg); redirectUrl = request.getContextPath() + SSOConstants.INTERACTIVE_CHANGE_PASSWD_FORM_URI; } log.debug("Redirecting to url: {}", redirectUrl); response.sendRedirect(redirectUrl); }
Source:
<code>private static Properties loadBuildProperties() { Properties prop = new Properties(); ClassLoader loader = <START> Thread.currentThread().getContextClassLoader(); <END> try { prop.load(loader.getResourceAsStream("git.properties")); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }</code><technical_language>Update.class.getClassloader() more correct in this case, want get properties fiel is packaged in jar this class</technical_language>

Target:
private static Properties loadBuildProperties() { Properties prop = new Properties(); try { prop.load(Update.class.getClassLoader().getResourceAsStream("git.properties")); } catch (IOException e) { log.warn("Failed to load properties file"); } return prop; }
Source:
<code><START> public DataCenterListResponseHandler(DateCodecFactory dateCodec) { <END> super(dateCodec); this.dataCenters = Lists.newArrayList(); }</code><technical_language>Injected constructor package private</technical_language>

Target:
DataCenterListResponseHandler(DateCodecFactory dateCodec) { super(dateCodec); this.dataCenters = Lists.newArrayList(); }
Source:
<code>public static RadioPlayerFeedCompiler valueOf(FileType type) { checkState(compilerMap != null, "Compiler map not initialised"); <START> return checkNotNull(compilerMap.get(type), "No compiler for type " + type); <END> }</code><technical_language>this throw IllegalArgumentException a NullPointerException if a compiler exist for type</technical_language>

Target:
public static RadioPlayerFeedCompiler valueOf(FileType type) { checkState(compilerMap != null, "Compiler map not initialised"); RadioPlayerFeedCompiler compiler = compilerMap.get(type); checkArgument(compiler != null, "No compiler for type " + type); return compiler; }
Source:
<code>public Map<String, Map<String, Integer>> dumpHashTableStats() { <START> Map<String, Map<String, Integer>> ret = new HashMap<String, Map<String, Integer>>(); <END> if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }</code><technical_language>I diamond operator</technical_language>

Target:
public Map<String, Map<String, Integer>> dumpHashTableStats() { Map<String, Map<String, Integer>> ret = new HashMap<>(); if (groupStates != null) { ret.put(groupStates.name, groupStates.dumpStats()); } return ret; }
Source:
<code>private Integer getCounterValue(Request request) { try { <START> int counter = Integer.parseInt(request.params("pipeline_counter"), 10); <END> if (counter < 1) { throw new UnprocessableEntityException("The pipeline counter cannot be less than 1."); } return counter; } catch (NumberFormatException ex) { throw new UnprocessableEntityException("The pipeline counter should be an integer."); } }</code><technical_language>Do need pass radix? simply Integer.parseInt(request.params("pipeline_counter"))? where, default, converts input a signed decimal integer</technical_language>

Target:
private Integer getCounterValue(Request request) { try { int counter = Integer.parseInt(request.params("pipeline_counter")); if (counter < 1) { throw new UnprocessableEntityException("The pipeline counter cannot be less than 1."); } return counter; } catch (NumberFormatException ex) { throw new UnprocessableEntityException("The pipeline counter should be an integer."); } }
Source:
<code>public void alterAddColumnToCloudUsage(final Connection conn) { final String alterTableSql = "ALTER TABLE `cloud_usage`.`cloud_usage` ADD COLUMN `quota_calculated` tinyint(1) DEFAULT 0 NOT NULL COMMENT 'quota calculation status'"; try (PreparedStatement pstmt = conn.prepareStatement(alterTableSql)) { pstmt.executeUpdate(); <START> s_logger.info("Altered usage table and added column quota_calculated"); <END> } catch (SQLException e) { if (e.getMessage().contains("quota_calculated")) { s_logger.warn("Usage table already has a column called quota_calculated"); } else { throw new CloudRuntimeException("Unable to create column quota_calculated", e); } } }</code><technical_language>This log statement reflect actual name of table, cloud_usage, altered in order avoid ambiguity</technical_language>

Target:
public void alterAddColumnToCloudUsage(final Connection conn) { final String alterTableSql = "ALTER TABLE `cloud_usage`.`cloud_usage` ADD COLUMN `quota_calculated` tinyint(1) DEFAULT 0 NOT NULL COMMENT 'quota calculation status'"; try (PreparedStatement pstmt = conn.prepareStatement(alterTableSql)) { pstmt.executeUpdate(); s_logger.info("Altered cloud_usage.cloud_usage table and added column quota_calculated"); } catch (SQLException e) { if (e.getMessage().contains("quota_calculated")) { s_logger.warn("cloud_usage.cloud_usage table already has a column called quota_calculated"); } else { throw new CloudRuntimeException("Unable to create column quota_calculated in table cloud_usage.cloud_usage", e); } } }
Source:
<code>private void openProposalPopupAsync() { <START> getControl().getDisplay().asyncExec(new Runnable() { @Override public void run() <END> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } } }); }</code><technical_language>lambda instead private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }</technical_language>

Target:
private void openProposalPopupAsync() { getControl().getDisplay().asyncExec(() -> { Control control = getControl(); if (control != null && !control.isDisposed()) { contentProposer.openProposalPopup(); } }); }
Source:
<code>public List<Result> allResults() { <START> randomAccess = true; <END> return new ResultSetList(); }</code><technical_language>randomAccess is thread safe</technical_language>

Target:
public List<Result> allResults() { List<Result> results = new ArrayList<>(); Result result; while ((result = next()) != null) results.add(result); return results; }
Source:
<code>public void setup(final String headerKey, final String labelKey) { getView().setHeader(translationService.format(headerKey)); getView().setLabel(translationService.format(labelKey)); <START> superSetup(); <END> }</code><technical_language>here, _setup_</technical_language>

Target:
public void setup(final String headerKey, final String labelKey) { getView().setHeader(translationService.format(headerKey)); getView().setLabel(translationService.format(labelKey)); setup(); }
Source:
<code>public static BranchOptionsEnum fromInitValue(String initKey) { for (BranchOptionsEnum optEnum : values()) { if (optEnum.origKeyName.equals(initKey)) { return optEnum; } } <START> throw new IllegalArgumentException(String.format("Incorrect BranchOptionEnum value")); <END> }</code><technical_language>want concatenate initKey this for debugging maintenance: "Incorrect BranchOptionEnum value: " + initKey</technical_language>

Target:
public static BranchOptionsEnum fromInitValue(String initKey) { for (BranchOptionsEnum optEnum : values()) { if (optEnum.origKeyName.equals(initKey)) { return optEnum; } } throw new IllegalArgumentException(String.format("Incorrect BranchOptionEnum value: " + initKey)); }
Source:
<code><START> protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) <END> throws JSchException { if (defaultJSch == null) { defaultJSch = createDefaultJSch(fs); for (final Object name : defaultJSch.getIdentityNames()) { byIdentityFile.put((String) name, defaultJSch); } } final File identityFile = hc.getIdentityFile(); if (identityFile == null) { return defaultJSch; } final String identityKey = identityFile.getAbsolutePath(); JSch jsch = byIdentityFile.get(identityKey); if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository()); jsch.addIdentity(identityKey); byIdentityFile.put(identityKey, jsch); } return jsch; }</code><technical_language>Style-nit: Please revert this reflow of method declaration</technical_language>

Target:
protected JSch getJSch(final OpenSshConfig.Host hc, FS fs) throws JSchException { if (defaultJSch == null) { defaultJSch = createDefaultJSch(fs); for (Object name : defaultJSch.getIdentityNames()) byIdentityFile.put((String) name, defaultJSch); } final File identityFile = hc.getIdentityFile(); if (identityFile == null) return defaultJSch; final String identityKey = identityFile.getAbsolutePath(); JSch jsch = byIdentityFile.get(identityKey); if (jsch == null) { jsch = new JSch(); jsch.setHostKeyRepository(defaultJSch.getHostKeyRepository()); jsch.addIdentity(identityKey); byIdentityFile.put(identityKey, jsch); } return jsch; }
Source:
<code>public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { List<ServiceName> failures = new ArrayList<>(); ServiceRegistry registry = context.getServiceRegistry(false); for (ServiceName serviceName : requiredServices) { try { ServiceController<?> controller = registry.getService(serviceName); if (controller == null || State.UP != controller.getState()) { failures.add(serviceName); } } catch (ServiceNotFoundException ex) { failures.add(serviceName); } } if (failures.containsAll(requiredServices)) { context.setRollbackOnly(); <START> ModelNode requiredServicesNode = context.getFailureDescription().get(ROOT_LOGGER.missingRequiredServices()); <END> for (ServiceName serviceName : failures) { requiredServicesNode.add(serviceName.getCanonicalName()); } } }</code><technical_language>need deal failure description. existing verification steps output correct failure description. this verification needs do is force rollback context.setRollbackOnly()</technical_language>

Target:
public void execute(OperationContext context, ModelNode operation) throws OperationFailedException { Boolean attachment = context.getAttachment(MANAGEMENT_INTERFACE_KEY); if (attachment == null ||!context.getAttachment(MANAGEMENT_INTERFACE_KEY)) { context.setRollbackOnly(); } }
Source:
<code><START> static private int requireNonNullInt(String required, String message) throws ConfigurationRuntimeException { <END> if (required == null) throw new ConfigurationRuntimeException(message); try { return Integer.parseInt(required); } catch (NumberFormatException e) { throw new ConfigurationRuntimeException(message); } }</code><technical_language>above, a general note scope is keyword, static</technical_language>

Target:
private static int requireNonNullInt(String required, String message) throws ConfigurationRuntimeException { if (required == null) throw new ConfigurationRuntimeException(message); try { return Integer.parseInt(required); } catch (NumberFormatException e) { throw new ConfigurationRuntimeException(message); } }
Source:
<code>public Optional<String> getBrokerServiceName(TieredBrokerConfig tierConfig, Query query) { final int priority = QueryContexts.getPriority(query); if (priority < minPriority) { return Optional.of( <START> tierConfig.getDefaultBrokerServiceName() <END> ); } else if (priority >= maxPriority) { return Optional.of(tierConfig.getDefaultBrokerServiceName()); } return Optional.absent(); }</code><technical_language>Logging helpful</technical_language>

Target:
public Optional<String> getBrokerServiceName(TieredBrokerConfig tierConfig, Query query) { final int priority = QueryContexts.getPriority(query); if (priority < minPriority || priority > maxPriority) { return Optional.of( tierConfig.getDefaultBrokerServiceName() ); } return Optional.absent(); }
Source:
<code>public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; <START> for (int i = 0; i < 7; i++) { <END> if (ti.getText(i).contains(text)) { return true; } } return false; }</code><technical_language>is 7 in this context</technical_language>

Target:
public boolean matches(Object item) { AbstractTableItem ti = (AbstractTableItem) item; if (ti.getText().contains(text)) { return true; } return false; }
Source:
<code>private static AddModuleWizard createImportWizard(@NotNull VirtualFile file) throws IOException, ConfigurationException { VirtualFile target = ProjectImportUtil.findImportTarget(file); if (target == null) { return null; } VirtualFile targetDir = target.isDirectory() ? target : target.getParent(); File targetDirFile = VfsUtilCore.virtualToIoFile(targetDir); <START> if (ADTModuleImporter.isADTProjectLocation(file)) { <END> importAdtProject(file); } else if (GradleImport.isEclipseProjectDir(targetDirFile) && targetDir.findChild(SdkConstants.FN_BUILD_GRADLE) == null && !ApplicationManager.getApplication().isUnitTestMode()) { String message = String.format("%1$s is in an Eclipse project, but not an Android Eclipse project.\n\n" + "Please select the directory of an Android Eclipse project" + "(which for example will contain\nan AndroidManifest.xml file) and try again.", file.getPath()); Messages.showErrorDialog(message, "Import Project"); } else if (GradleModuleImporter.isGradleProject(target)) { GradleProjectImporter gradleImporter = GradleProjectImporter.getInstance(); gradleImporter.importProject(file); } else { return importWithExtensions(file); } return null; }</code><technical_language>capitalize acronyms, ADTModuleImporter => AdtModuleImporter, isADTProjectLocation => isAdtProjectLocation</technical_language>

Target:
private static AddModuleWizard createImportWizard(@NotNull VirtualFile file) throws IOException, ConfigurationException { VirtualFile target = ProjectImportUtil.findImportTarget(file); if (target == null) { return null; } VirtualFile targetDir = target.isDirectory() ? target : target.getParent(); File targetDirFile = VfsUtilCore.virtualToIoFile(targetDir); if (AdtModuleImporter.isAdtProjectLocation(file)) { importAdtProject(file); } else if (GradleImport.isEclipseProjectDir(targetDirFile) && targetDir.findChild(SdkConstants.FN_BUILD_GRADLE) == null && !ApplicationManager.getApplication().isUnitTestMode()) { String message = String.format("%1$s is an Eclipse project, but not an Android Eclipse project.\n\n" + "Please select the directory of an Android Eclipse project" + "(which for example will contain\nan AndroidManifest.xml file) and try again.", file.getPath()); Messages.showErrorDialog(message, "Import Project"); } else if (GradleModuleImporter.isGradleProject(target)) { GradleProjectImporter gradleImporter = GradleProjectImporter.getInstance(); gradleImporter.importProject(file); } else { return importWithExtensions(file); } return null; }
Source:
<code><START> public void trackFirmwares(final Map<String, Integer> seenFirmwares) { <END> trackDeviceFirmwares(ImmutableMap.copyOf(seenFirmwares)); }</code><technical_language>public/private methods if accept params calls other</technical_language>

Target:
public void trackFirmwares(final Map<String, Integer> seenFirmwares) { Jedis jedis = null; try { jedis = jedisPool.getResource(); final Pipeline pipe = jedis.pipelined(); pipe.multi(); for(Map.Entry<String, Integer> entry : seenFirmwares.entrySet()) { pipe.sadd(ActiveDevicesTrackerConfiguration.FIRMWARES_SEEN_SET_KEY, entry.getValue().toString()); pipe.zadd(entry.getValue().toString(), DateTime.now().getMillis(), entry.getKey()); } pipe.exec(); }catch (JedisDataException exception) { LOGGER.error("Failed getting data out of redis: {}", exception.getMessage()); jedisPool.returnBrokenResource(jedis); return; } catch(Exception exception) { LOGGER.error("Unknown error connection to redis: {}", exception.getMessage()); jedisPool.returnBrokenResource(jedis); return; } finally { try{ jedisPool.returnResource(jedis); }catch (JedisConnectionException e) { LOGGER.error("Jedis Connection Exception while returning resource to pool. Redis server down?"); } } LOGGER.debug("Tracked device firmware versions", seenFirmwares.size()); }
Source:
<code>public Collection<StatisticDescriptor> getDescriptors() { Set<StatisticDescriptor> descriptors = new HashSet<StatisticDescriptor>(); <START> for (Map.Entry<String, ValueStatistic<? extends Number>> entry : statistics.entrySet()) { <END> String fullStatName = entry.getKey(); StatisticType type = statisticTypes.get(fullStatName); descriptors.add(new StatisticDescriptor(fullStatName, type.name())); } return descriptors; }</code><technical_language>Please add a set size</technical_language>

Target:
public Collection<StatisticDescriptor> getDescriptors() { Set<StatisticDescriptor> descriptors = new HashSet<StatisticDescriptor>(statistics.size()); for (Map.Entry<String, ValueStatistic<? extends Number>> entry : statistics.entrySet()) { String fullStatName = entry.getKey(); StatisticType type = statisticTypes.get(fullStatName); descriptors.add(new StatisticDescriptor(fullStatName, type.name())); } return descriptors; }
Source:
<code>public boolean isFragment(Bundle bundle) { <START> PlatformAdmin platformAdmin = getPlatformAdmin(); if (platformAdmin == null) return false; <END> return false; }</code><technical_language>This incomplete. be: BundleRevisions bundleRevisions = bundle.adapt(BundleRevisions.class); List<BundleRevision> revisions = bundleRevisions.getRevisions(); if (revisions.isEmpty()) { // bundle is uninstalled current users; return false return false; } return (revisions.get(0).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0;</technical_language>

Target:
public boolean isFragment(Bundle bundle) { BundleRevisions bundleRevisions = bundle.adapt(BundleRevisions.class); List<BundleRevision> revisions = bundleRevisions.getRevisions(); if (revisions.isEmpty()) { return false; } return (revisions.get(0).getTypes() & BundleRevision.TYPE_FRAGMENT) != 0; }
Source:
<code>protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = null; try { get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH); Log.d(TAG, "URL ------> " + client.getBaseUri() + ShareUtils.SHARING_API_PATH); get.setQueryString(new NameValuePair[] { new NameValuePair(PARAM_PATH, mRemoteFilePath), new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)), new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles)) }); <START> get.addRequestHeader(HEADER_OCS_API, HEADER_OCS_API_VALUE); <END> status = client.executeMethod(get); if(isSuccess(status)) { String response = get.getResponseBodyAsString(); Log.d(TAG, "Successful response: " + response); result = new RemoteOperationResult(ResultCode.OK); InputStream is = new ByteArrayInputStream(response.getBytes()); ShareXMLParser xmlParser = new ShareXMLParser(); mShares = xmlParser.parseXMLResponse(is); if (mShares != null) { Log.d(TAG, "Shares: " + mShares.size()); result = new RemoteOperationResult(ResultCode.OK); ArrayList<Object> sharesObjects = new ArrayList<Object>(); for (OCShare share: mShares) { sharesObjects.add(share); } result.setData(sharesObjects); } } else { result = new RemoteOperationResult(false, status, get.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log.e(TAG, "Exception while Creating New Share", e); } finally { if (get != null) { get.releaseConnection(); } } return result; }</code><technical_language>ident</technical_language>

Target:
protected RemoteOperationResult run(OwnCloudClient client) { RemoteOperationResult result = null; int status = -1; GetMethod get = null; try { get = new GetMethod(client.getBaseUri() + ShareUtils.SHARING_API_PATH); Log.d(TAG, "URL ------> " + client.getBaseUri() + ShareUtils.SHARING_API_PATH); get.setQueryString(new NameValuePair[] { new NameValuePair(PARAM_PATH, mRemoteFilePath), new NameValuePair(PARAM_RESHARES, String.valueOf(mReshares)), new NameValuePair(PARAM_SUBFILES, String.valueOf(mSubfiles)) }); get.addRequestHeader(OCS_API_HEADER, OCS_API_HEADER_VALUE); status = client.executeMethod(get); if(isSuccess(status)) { String response = get.getResponseBodyAsString(); Log.d(TAG, "Successful response: " + response); result = new RemoteOperationResult(ResultCode.OK); InputStream is = new ByteArrayInputStream(response.getBytes()); ShareXMLParser xmlParser = new ShareXMLParser(); mShares = xmlParser.parseXMLResponse(is); if (mShares != null) { Log.d(TAG, "Shares: " + mShares.size()); result = new RemoteOperationResult(ResultCode.OK); ArrayList<Object> sharesObjects = new ArrayList<Object>(); for (OCShare share: mShares) { sharesObjects.add(share); } result.setData(sharesObjects); } } else { result = new RemoteOperationResult(false, status, get.getResponseHeaders()); } } catch (Exception e) { result = new RemoteOperationResult(e); Log.e(TAG, "Exception while Creating New Share", e); } finally { if (get != null) { get.releaseConnection(); } } return result; }
Source:
<code>protected void applyRecoverStrategy(final Channel channel) throws MuleException { MuleMessage currentMessage = RequestContext.getEvent().getMessage(); Long deliveryTag = getDeliveryTagOrFail(currentMessage, NACK_CHANNEL_ACTION); try { switch (recoverStrategy) { case NONE : try { <START> channel.txRollback(); <END> if (logger.isDebugEnabled()) { logger.debug("Rolled back AMQP transaction (" + recoverStrategy + ") on channel: " + channel); } } catch (final IOException ioe) { throw new TransactionException(CoreMessages.transactionRollbackFailed(), ioe); } break; case NO_REQUEUE : channel.basicReject(deliveryTag,false); channel.txCommit(); break; case REQUEUE : channel.basicReject(deliveryTag, true); channel.txCommit(); break; } if ((recoverStrategy != NONE) && (logger.isDebugEnabled())) { logger.debug("Applied " + recoverStrategy + " recover strategy on channel: " + channel); } } catch (final IOException ioe) { logger.warn("Failed to recover channel " + channel + " after rollback (recoverStrategy is " + recoverStrategy + ")"); } }</code><technical_language>in case of a rollback is needed? other transactional operations involved in transaction (for example AMQP requester) committed if transaction fails</technical_language>

Target:
protected void applyRecoverStrategy(final Channel channel) throws MuleException { MuleMessage currentMessage = RequestContext.getEvent().getMessage(); Long deliveryTag = getDeliveryTagOrFail(currentMessage, NACK_CHANNEL_ACTION); try { switch (recoverStrategy) { case NONE : break; case NO_REQUEUE : channel.basicReject(deliveryTag,false); channel.txCommit(); break; case REQUEUE : channel.basicReject(deliveryTag, true); channel.txCommit(); break; } if ((recoverStrategy != NONE) && (logger.isDebugEnabled())) { logger.debug("Applied " + recoverStrategy + " recover strategy on channel: " + channel); } } catch (final IOException ioe) { logger.warn("Failed to recover channel " + channel + " after rollback (recoverStrategy is " + recoverStrategy + ")"); } }
Source:
<code>public void showProblemColumns(Column... columns) { if (columns != null && columns.length > 0) { List<String> problemColumns = getProblemColumns(); <START> openConfigureColumnsShell(); <END> for (Column column: columns) { if (!problemColumns.contains(column.toString())) { for (TableItem item: new DefaultTable(0).getItems()) { if (column.toString().equals(item.getText())) { item.select(); break; } } new PushButton("Show ->").click(); } } confirmChangesAndCloseConfigureColumnsShell(); } }</code><technical_language>create array of column headers shown currently hidden new DefaultTable(0).select(columnsToShowArray) more readable RedDeer API. in case columns needed show dialog is opened. applies for hideProblemsCountMethod()</technical_language>

Target:
public void showProblemColumns(Column... columns) { String[] columnsToShow = getColumnsToShow(columns); if (columnsToShow.length > 0) { openConfigureColumnsShell(); new DefaultTable(0).select(columnsToShow); new PushButton("Show ->").click(); confirmChangesAndCloseConfigureColumnsShell(); } }
Source:
<code>public void setProgress(final int val, final int max) { boolean processing = getLegacyService().setProcessingEvents(true); if (processing) return; try { final IJ1Helper ij1helper = helper(); if (ij1helper != null) ij1helper.setProgress(val, max); } finally { <START> final LegacyService LegacyService = getLegacyService(); <END> if (LegacyService != null) LegacyService.setProcessingEvents(processing); } }</code><technical_language>Lower-case variable, above</technical_language>

Target:
public void setProgress(final int val, final int max) { boolean processing = getLegacyService().setProcessingEvents(true); if (processing) return; try { final IJ1Helper ij1Helper = helper(); if (ij1Helper != null) ij1Helper.setProgress(val, max); } finally { final LegacyService legacyService = getLegacyService(); if (legacyService != null) legacyService.setProcessingEvents(processing); } }
Source:
<code>public static String getGroupId(GroupApi groupApi) { for ( GroupState state : groupApi.listGroupStates() ) { Group g = groupApi.get(state.getId()); for ( ScalingPolicyResponse policy : g.getScalingPolicies() ) { if (policy.getName().equals(NAME)) return g.getId(); } } <START> throw new RuntimeException("Group not found"); <END> }</code><technical_language>[minor] IllegalArgException</technical_language>

Target:
public static String getGroupId(GroupApi groupApi) { for ( GroupState state : groupApi.listGroupStates() ) { Group g = groupApi.get(state.getId()); for ( ScalingPolicyResponse policy : g.getScalingPolicies() ) { if (policy.getName().equals(NAME)) return g.getId(); } } throw new IllegalArgumentException("Group not found"); }
Source:
<code>public static SmallIntSet of(int i1) { <START> SmallIntSet set = new SmallIntSet(1); <END> set.set(i1); return set; }</code><technical_language>i1 + 1? in other of(...) methods, constructor parameter is end of range</technical_language>

Target:
public static SmallIntSet of(int i1) { SmallIntSet set = new SmallIntSet(); set.set(i1); return set; }
Source:
<code>public void adjustViewport( @NotNull final SPath path, final LineRange range, final TextSelection selection) { Set<String> visibleFilePaths = new HashSet<>(); for (VirtualFile virtualFile : projectAPI.getSelectedFiles()) { visibleFilePaths.add(virtualFile.getPath()); } VirtualFile passedFile = VirtualFileConverter.convertToVirtualFile(path); if (passedFile == null) { LOG.warn( "Ignoring request to adjust viewport as no valid VirtualFile could be found for " + path + " - given range: " + range + ", given selection: " + selection); return; } Editor editor = editorPool.getEditor(path); if (!visibleFilePaths.contains(passedFile.getPath())) { localEditorStatusChangeHandler.queueViewPortChange( passedFile.getPath(), editor, range, selection); return; } if (editor == null) { LOG.warn( "Failed to adjust viewport for " + path + " as it is not known to the editor pool even though it is currently open"); return; } <START> ApplicationManager.getApplication() <END> .invokeAndWait(() -> localEditorManipulator.adjustViewport(editor, range, selection)); }</code><technical_language>executeInUIThreadSynchronous ApplicationManager... remove wrapper</technical_language>

Target:
public void adjustViewport( @NotNull final SPath path, final LineRange range, final TextSelection selection) { Set<String> visibleFilePaths = new HashSet<>(); for (VirtualFile virtualFile : projectAPI.getSelectedFiles()) { visibleFilePaths.add(virtualFile.getPath()); } VirtualFile passedFile = VirtualFileConverter.convertToVirtualFile(path); if (passedFile == null) { LOG.warn( "Ignoring request to adjust viewport as no valid VirtualFile could be found for " + path + " - given range: " + range + ", given selection: " + selection); return; } Editor editor = editorPool.getEditor(path); if (!visibleFilePaths.contains(passedFile.getPath())) { localEditorStatusChangeHandler.queueViewPortChange( passedFile.getPath(), editor, range, selection); return; } if (editor == null) { LOG.warn( "Failed to adjust viewport for " + path + " as it is not known to the editor pool even though it is currently open"); return; } executeInUIThreadSynchronous( () -> localEditorManipulator.adjustViewport(editor, range, selection)); }
Source:
<code>private void reportTimer(long timestamp, String name, Timer timer) { final Snapshot snapshot = timer.getSnapshot(); report(timestamp, name, "count,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", <START> "%d" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + <END> separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "%f" + separator + "calls/%s" + separator + "%s", timer.getCount(), convertDuration(snapshot.getMax()), convertDuration(snapshot.getMean()), convertDuration(snapshot.getMin()), convertDuration(snapshot.getStdDev()), convertDuration(snapshot.getMedian()), convertDuration(snapshot.get75thPercentile()), convertDuration(snapshot.get95thPercentile()), convertDuration(snapshot.get98thPercentile()), convertDuration(snapshot.get99thPercentile()), convertDuration(snapshot.get999thPercentile()), convertRate(timer.getMeanRate()), convertRate(timer.getOneMinuteRate()), convertRate(timer.getFiveMinuteRate()), convertRate(timer.getFifteenMinuteRate()), getRateUnit(), getDurationUnit()); }</code><technical_language>do String.join avoid repetition? This method a StringBuilder hood, provide similar performance concatenation</technical_language>

Target:
private void reportTimer(long timestamp, String name, Timer timer) { final Snapshot snapshot = timer.getSnapshot(); report(timestamp, name, "count,max,mean,min,stddev,p50,p75,p95,p98,p99,p999,mean_rate,m1_rate,m5_rate,m15_rate,rate_unit,duration_unit", timerFormat, timer.getCount(), convertDuration(snapshot.getMax()), convertDuration(snapshot.getMean()), convertDuration(snapshot.getMin()), convertDuration(snapshot.getStdDev()), convertDuration(snapshot.getMedian()), convertDuration(snapshot.get75thPercentile()), convertDuration(snapshot.get95thPercentile()), convertDuration(snapshot.get98thPercentile()), convertDuration(snapshot.get99thPercentile()), convertDuration(snapshot.get999thPercentile()), convertRate(timer.getMeanRate()), convertRate(timer.getOneMinuteRate()), convertRate(timer.getFiveMinuteRate()), convertRate(timer.getFifteenMinuteRate()), getRateUnit(), getDurationUnit()); }
Source:
<code>private void makeList(int minLen, int maxLen, String baseCase, BaseCase baseCaseObj) { for (int x = minLen; x <= maxLen; x++) { while (listindex[0] < list.length) { try { showString(x, baseCase, baseCaseObj); incrementCounter(x); Thread.sleep(20); } catch (InterruptedException ex) { <START> LOG.error("makeList " + ex.toString()); <END> } } initIndex(); } }</code><technical_language>suggest debug, thread interrupted is necessarily issue/bug</technical_language>

Target:
private void makeList(int minLen, int maxLen, String baseCase, BaseCase baseCaseObj) { for (int x = minLen; x <= maxLen; x++) { while (listindex[0] < list.length) { try { showString(x, baseCase, baseCaseObj); incrementCounter(x); Thread.sleep(20); } catch (InterruptedException ex) { if (LOG.isDebugEnabled()) { LOG.error("makeList " + ex.toString()); } } } initIndex(); } }
Source:
<code>private long getDistanceDifferentTimelines(final NakadiCursor initialCursor, final NakadiCursor finalCursor) { long distance = 0; distance += totalEventsInTimeline(initialCursor) - numberOfEventsBeforeCursor(initialCursor); final String partitionString = initialCursor.getPartition(); for (int order = initialCursor.getTimeline().getOrder() + 1; order < finalCursor.getTimeline().getOrder(); order++) { <START> final Timeline timeline = getTimeline(initialCursor.getTopic(), order); <END> distance += totalEventsInTimeline(timeline, partitionString); } distance += numberOfEventsBeforeCursor(finalCursor); return distance; }</code><technical_language>@rcillo testing dies (topic is instead of event type)</technical_language>

Target:
private long getDistanceDifferentTimelines(final NakadiCursor initialCursor, final NakadiCursor finalCursor) { long distance = 0; if (numberOfEventsBeforeCursor(initialCursor) < 0) { distance += totalEventsInTimeline(initialCursor); } else { distance += totalEventsInTimeline(initialCursor) - numberOfEventsBeforeCursor(initialCursor) - 1; } final String partitionString = initialCursor.getPartition(); for (int order = initialCursor.getTimeline().getOrder() + 1; order < finalCursor.getTimeline().getOrder(); order++) { final Timeline timeline = getTimeline(initialCursor.getEventType(), order); distance += totalEventsInTimeline(timeline, partitionString); } distance += numberOfEventsBeforeCursor(finalCursor) + 1; return distance; }
Source:
<code>public void testShowTablesMultiTenant() throws Exception { String tenantId2 = "T_" + generateUniqueName(); String secondTenantConnectionURL = PHOENIX_JDBC_TENANT_SPECIFIC_URL.replace(TENANT_ID, tenantId2); String tenantTable2 = "V_" + generateUniqueName(); createTestTable(secondTenantConnectionURL, TENANT_TABLE_DDL.replace(TENANT_TABLE_NAME, tenantTable2)); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { Set<String> tables = new HashSet<>(); ResultSet rs = conn.prepareStatement("show tables").executeQuery(); <START> while (rs.next()) tables.add(rs.getString("TABLE_NAME")); <END> assertTrue(tables.contains(PARENT_TABLE_NAME)); assertTrue(tables.contains(TENANT_TABLE_NAME)); assertTrue(tables.contains(tenantTable2)); } try (Connection conn = DriverManager.getConnection(secondTenantConnectionURL, props)) { Set<String> tables = new HashSet<>(); ResultSet rs = conn.prepareStatement("show tables").executeQuery(); while (rs.next()) tables.add(rs.getString("TABLE_NAME")); assertTrue(tables.contains(PARENT_TABLE_NAME)); assertFalse(tables.contains(TENANT_TABLE_NAME)); assertTrue(tables.contains(tenantTable2)); } }</code><technical_language>nit: please put loop body in brackets</technical_language>

Target:
public void testShowTablesMultiTenant() throws Exception { String tenantId2 = "T_" + generateUniqueName(); String secondTenantConnectionURL = PHOENIX_JDBC_TENANT_SPECIFIC_URL.replace(TENANT_ID, tenantId2); String tenantTable2 = "V_" + generateUniqueName(); createTestTable( secondTenantConnectionURL, TENANT_TABLE_DDL.replace(TENANT_TABLE_NAME, tenantTable2)); Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES); try (Connection conn = DriverManager.getConnection(getUrl(), props)) { Set<String> tables = new HashSet<>(); ResultSet rs = conn.prepareStatement("show tables").executeQuery(); while (rs.next()) { tables.add(rs.getString("TABLE_NAME")); } assertTrue(tables.contains(PARENT_TABLE_NAME)); assertTrue(tables.contains(TENANT_TABLE_NAME)); assertTrue(tables.contains(tenantTable2)); } try (Connection conn = DriverManager.getConnection(secondTenantConnectionURL, props)) { Set<String> tables = new HashSet<>(); ResultSet rs = conn.prepareStatement("show tables").executeQuery(); while (rs.next()) { tables.add(rs.getString("TABLE_NAME")); } assertTrue(tables.contains(PARENT_TABLE_NAME)); assertFalse(tables.contains(TENANT_TABLE_NAME)); assertTrue(tables.contains(tenantTable2)); } }
Source:
<code>public ResultScanner<FlatRow> readFlatRows(ReadRowsRequest request) { ResponseQueueReader reader = new ResponseQueueReader(); ScanHandler scanHandler = createReadRowsRetryListener(request, reader); <START> reader.setScanHandler(scanHandler); <END> return new ResumingStreamingResultScanner(reader, scanHandler); }</code><technical_language>avoid scanner & reader calling out ScanHandler(RetryingReadRowsOperation) scanner call reader reader delegates ScanHandler</technical_language>

Target:
public ResultScanner<FlatRow> readFlatRows(ReadRowsRequest request) { final ResponseQueueReader reader = new ResponseQueueReader(); RetryingReadRowsOperation operation = createReadRowsRetryListener(request, reader); operation.setResultObserver(new StreamObserver<ReadRowsResponse>(){ @Override public void onNext(ReadRowsResponse value) { reader.addRequestResultMarker(); } @Override public void onError(Throwable t) @Override public void onCompleted() }); operation.getAsyncResult(); return new ResumingStreamingResultScanner(reader, operation); }
Source:
<code>public void validateWebAnnotation(Annotation webAnnotation) throws ParamValidationException, RequestBodyValidationException { if (webAnnotation.getCanonical() != null) { try { URI cannonicalUri = URI.create(webAnnotation.getCanonical()); if (!cannonicalUri.isAbsolute()) throw new ParamValidationException("The canonical URI is not absolute:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.CANONICAL, webAnnotation.getCanonical() }); } catch (IllegalArgumentException e) { throw new ParamValidationException("Error when validating canonical URI:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.CANONICAL, webAnnotation.getCanonical() }, e); } } if (webAnnotation.getVia() != null) { if (webAnnotation.getVia() instanceof String[]) { for (String via : webAnnotation.getVia()) { if (!(UriUtils.isUrl(via))) throw new ParamValidationException("This is not a valid URL:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.VIA, via }); } } } switch (webAnnotation.getMotivationType()) { case LINKING: if (webAnnotation.getTarget() != null) { if (webAnnotation.getTarget().getValue() != null) validateResource(webAnnotation.getTarget().getValue()); if (webAnnotation.getTarget().getValues() != null) for (String url : webAnnotation.getTarget().getValues()) { validateResource(url); } } break; case TAGGING: validateTag(webAnnotation); break; case TRANSCRIBING: validateTranscribing(webAnnotation); <START> validateEdmRights(webAnnotation); <END> break; default: break; } }</code><technical_language>validation of edmRights included in vaidateTranscription method</technical_language>

Target:
public void validateWebAnnotation(Annotation webAnnotation) throws ParamValidationException, RequestBodyValidationException { if (webAnnotation.getCanonical() != null) { try { URI cannonicalUri = URI.create(webAnnotation.getCanonical()); if (!cannonicalUri.isAbsolute()) throw new ParamValidationException("The canonical URI is not absolute:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.CANONICAL, webAnnotation.getCanonical() }); } catch (IllegalArgumentException e) { throw new ParamValidationException("Error when validating canonical URI:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.CANONICAL, webAnnotation.getCanonical() }, e); } } if (webAnnotation.getVia() != null) { if (webAnnotation.getVia() instanceof String[]) { for (String via : webAnnotation.getVia()) { if (!(UriUtils.isUrl(via))) throw new ParamValidationException("This is not a valid URL:", I18nConstants.ANNOTATION_VALIDATION, new String[] { WebAnnotationFields.VIA, via }); } } } switch (webAnnotation.getMotivationType()) { case LINKING: if (webAnnotation.getTarget() != null) { if (webAnnotation.getTarget().getValue() != null) validateResource(webAnnotation.getTarget().getValue()); if (webAnnotation.getTarget().getValues() != null) for (String url : webAnnotation.getTarget().getValues()) { validateResource(url); } } break; case TAGGING: validateTag(webAnnotation); break; case TRANSCRIBING: validateTranscription(webAnnotation); break; default: break; } }
Source:
<code>public Optional<Database> getDatabase(String databaseName) { try { return retry() .stopOn(NoSuchObjectException.class) .stopOnIllegalExceptions() .run("getDatabase", stats.getGetDatabase().wrap(() -> <START> wrapHMSCallable((HiveMetastoreClient client, ThriftHiveMetastoreStats stat) -> Optional.of(stat.getGetDatabase().wrapCall(() -> client.getDatabase(databaseName)))))); <END> } catch (NoSuchObjectException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }</code><technical_language>wrapMetastoreCallable</technical_language>

Target:
public Optional<Database> getDatabase(String databaseName) { try { return retry() .stopOn(NoSuchObjectException.class) .stopOnIllegalExceptions() .run("getDatabase", stats.getGetDatabase().wrap(() -> wrapMetastoreCallable((HiveMetastoreClient client, ThriftHiveMetastoreStats stat) -> Optional.of(stat.getGetDatabase().wrapCall(() -> client.getDatabase(databaseName)))))); } catch (NoSuchObjectException e) { return Optional.empty(); } catch (TException e) { throw new PrestoException(HIVE_METASTORE_ERROR, e); } catch (Exception e) { throw propagate(e); } }
Source:
<code>private boolean hasRowExpiredOnSource(Long sourceTS, Long ttl) { <START> long currentTS = System.currentTimeMillis(); <END> if (sourceTS + ttl < currentTS) { return true; } else { return false; } }</code><technical_language>this EnvironmentEdgeManager.currentTime()</technical_language>

Target:
protected boolean hasRowExpiredOnSource(Long sourceTS, Long ttl) { long currentTS = EnvironmentEdgeManager.currentTimeMillis(); return ttl != Integer.MAX_VALUE && sourceTS + ttl*1000 < currentTS; }