auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { if (context.isBooting()) { <START> populateHostControllerInfo(hostControllerInfo, context, operation, operation); <END> } else { context.reloadRequired(); } }</code><technical_language>This clearer if "model" param removed</technical_language>

Target:
protected void performRuntime(final OperationContext context, final ModelNode operation, final ModelNode model) throws OperationFailedException { if (context.isBooting()) { populateHostControllerInfo(hostControllerInfo, context, operation); } else { context.reloadRequired(); } }
Source:
<code>public static Pair<List<PartitionKey>, String> getPartitionKeyNamePair(String[] columns, String[] values) { Pair<List<PartitionKey>, String> pair = null; List<PartitionKey> partitionKeyList = TUtil.newList(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < columns.length; i++) { <START> PartitionKey partitionKey = new PartitionKey(); <END> partitionKey.setColumnName(columns[i]); partitionKey.setPartitionValue(values[i]); if (i > 0) { sb.append("/"); } sb.append(columns[i]).append("=").append(values[i]); partitionKeyList.add(partitionKey); } pair = new Pair<List<PartitionKey>, String>(partitionKeyList, sb.toString()); return pair; }</code><technical_language>PartitionKey is transient intermediate data for PartitionDesc. I PartitionKey is unnecessary. PartitionKeyProto PartitionKey</technical_language>

Target:
public static Pair<List<PartitionKeyProto>, String> getPartitionKeyNamePair(String[] columns, String[] values) { Pair<List<PartitionKeyProto>, String> pair = null; List<PartitionKeyProto> partitionKeyList = TUtil.newList(); StringBuilder sb = new StringBuilder(); for (int i = 0; i < columns.length; i++) { PartitionKeyProto.Builder builder = PartitionKeyProto.newBuilder(); builder.setColumnName(columns[i]); builder.setPartitionValue(values[i]); if (i > 0) { sb.append("/"); } sb.append(columns[i]).append("=").append(values[i]); partitionKeyList.add(builder.build()); } pair = new Pair<List<PartitionKeyProto>, String>(partitionKeyList, sb.toString()); return pair; }
Source:
<code>private void doLink(String res, String lnk) throws BuildException { final Path link = Paths.get(lnk); final Path target = Paths.get(res); final boolean alreadyExists = Files.exists(link); if (!alreadyExists) { try { Files.createSymbolicLink(link, target); } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to create symlink " + lnk + " to target " + res, e); } log("Unable to create symlink " + lnk + " to target " + res, e, Project.MSG_INFO); } return; } if (!overwrite) { log("Skipping symlink creation, since file at " + lnk + " already exists and overwrite is set to false", Project.MSG_INFO); return; } if (!Files.isSymbolicLink(link)) { <START> throw new BuildException("Cannot overwrite, as symlink, at " + lnk + " since the path already exists and isn't a symlink"); <END> } try { Files.delete(link); } catch (IOException e) { log("Failed to delete existing symlink at " + lnk, e, Project.MSG_DEBUG); } try { Files.createSymbolicLink(link, target); } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to create symlink " + lnk + " to target " + res, e); } log("Unable to create symlink " + lnk + " to target " + res, e, Project.MSG_INFO); } }</code><technical_language>this failOnError account</technical_language>

Target:
private void doLink(String res, String lnk) throws BuildException { final Path link = Paths.get(lnk); final Path target = Paths.get(res); final boolean alreadyExists = Files.exists(link); if (!alreadyExists) { try { Files.createSymbolicLink(link, target); } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to create symlink " + lnk + " to target " + res, e); } log("Unable to create symlink " + lnk + " to target " + res, e, Project.MSG_INFO); } return; } if (!overwrite) { log("Skipping symlink creation, since file at " + lnk + " already exists and overwrite is set to false", Project.MSG_INFO); return; } if (!Files.isSymbolicLink(link)) { final String errMessage = "Cannot overwrite " + lnk + " since the path already exists and isn't a symlink"; if (failonerror) { throw new BuildException(errMessage); } log(errMessage, Project.MSG_INFO); return; } try { deleteSymLink(link); } catch (IOException e) { log("Failed to delete existing symlink at " + lnk, e, Project.MSG_DEBUG); } try { Files.createSymbolicLink(link, target); } catch (IOException e) { if (failonerror) { throw new BuildException("Failed to create symlink " + lnk + " to target " + res, e); } log("Unable to create symlink " + lnk + " to target " + res, e, Project.MSG_INFO); } }
Source:
<code>public RemoteIOSWebDriver(ServerSideSession session, ResponseFinder... finders) { this.session = session; connectionKey = UUID.randomUUID().toString(); sync = new WebKitSyncronizer(this); MessageListener notification = new WebKitNotificationListener(this, sync, session); if (session.getDevice() instanceof RealDevice) { if (!Configuration.BETA_FEATURE) { Configuration.off(); } protocol = new RealDeviceProtocolImpl(notification, finders); } else { protocol = new SimulatorProtocolImpl(notification, finders); } Log perfLog = session.getLogManager().getLog(IOSLogManager.PERFORMANCE_LOG_TYPE); if (perfLog !=null) { <START> perfListener = new PerformanceListener(perfLog); <END> protocol.addListener(perfListener); } protocol.register(); sync.waitForSimToRegister(); sync.waitForSimToSendApps(); if (applications.size() == 1) { connect(applications.get(0).getBundleId()); } else { log.warning("session created but application size=" + applications.size()); } }</code><technical_language>Move listener creation LogManager, pass in need pass register listeners. need track of listeners registration -- get GC'd protocol dies</technical_language>

Target:
public RemoteIOSWebDriver(ServerSideSession session, ResponseFinder... finders) { this.session = session; connectionKey = UUID.randomUUID().toString(); sync = new WebKitSyncronizer(this); MessageListener notification = new WebKitNotificationListener(this, sync, session); if (session.getDevice() instanceof RealDevice) { if (!Configuration.BETA_FEATURE) { Configuration.off(); } protocol = new RealDeviceProtocolImpl(notification, finders); } else { protocol = new SimulatorProtocolImpl(notification, finders); } session.getLogManager().onProtocolCreated(protocol); protocol.register(); sync.waitForSimToRegister(); sync.waitForSimToSendApps(); if (applications.size() == 1) { connect(applications.get(0).getBundleId()); } else { log.warning("session created but application size=" + applications.size()); } }
Source:
<code>private static EntitlementManager newGlobalManager(ResourceUtils loader, BrooklynProperties brooklynProperties) { String type = brooklynProperties.getConfig(GLOBAL_ENTITLEMENT_MANAGER); if ("root".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(root()); if ("readonly".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(readOnly()); if ("minimal".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(minimal()); if (Strings.isNonBlank(type)) { try { Class<?> clazz = loader.getLoader().loadClass(type); <START> if (clazz.getConstructor(BrooklynProperties.class)!=null) { <END> return (EntitlementManager) clazz.getConstructor(BrooklynProperties.class).newInstance(brooklynProperties); } else { return (EntitlementManager) clazz.newInstance(); } } catch (Exception e) { throw Exceptions.propagate(e); } } throw new IllegalStateException("Invalid entitlement manager specified: '"+type+"'"); }</code><technical_language>Class.getConstructor throws NoSuchMethodException if found, returning null</technical_language>

Target:
private static EntitlementManager newGlobalManager(ResourceUtils loader, BrooklynProperties brooklynProperties) { String type = brooklynProperties.getConfig(GLOBAL_ENTITLEMENT_MANAGER); if ("root".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(root()); if ("readonly".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(readOnly()); if ("minimal".equalsIgnoreCase(type)) return new PerUserEntitlementManagerWithDefault(minimal()); if (Strings.isNonBlank(type)) { try { Class<?> clazz = loader.getLoader().loadClass(type); Optional<?> result = Reflections.invokeConstructorWithArgs(clazz, brooklynProperties); if (result.isPresent()) return (EntitlementManager) result.get(); return (EntitlementManager) clazz.newInstance(); } catch (Exception e) { throw Exceptions.propagate(e); } } throw new IllegalStateException("Invalid entitlement manager specified: '"+type+"'"); }
Source:
<code>synchronized Map<String, Long> getTimeCounts(long now) { <START> Map<String, Long> ret = new ConcurrentHashMap<>(); <END> long value = currentBucket.get(); long timeSpent = now - bucketStart; ret.put("600", readApproximateTime(value, timeSpent, tmTime, tmBuckets, 600 * 1000)); ret.put("10800", readApproximateTime(value, timeSpent, thTime, thBuckets, 10800 * 1000)); ret.put("86400", readApproximateTime(value, timeSpent, odTime, odBuckets, 86400 * 1000)); ret.put(":all-time", value + allTime); return ret; }</code><technical_language>ConcurrentHashMap is needed I think. This is a get function is synchronized</technical_language>

Target:
synchronized Map<String, Long> getTimeCounts(long now) { Map<String, Long> ret = new HashMap<>(); long value = currentBucket.get(); long timeSpent = now - bucketStart; ret.put("600", readApproximateTime(value, timeSpent, tmTime, tmBuckets, 600 * 1000)); ret.put("10800", readApproximateTime(value, timeSpent, thTime, thBuckets, 10800 * 1000)); ret.put("86400", readApproximateTime(value, timeSpent, odTime, odBuckets, 86400 * 1000)); ret.put(":all-time", value + allTime); return ret; }
Source:
<code>public synchronized void addTrigger(Trigger t) throws TriggerLoaderException { logger.info("Inserting trigger " + t.toString() + " into db."); SQLTransaction<Long> insertAndGetLastID = transOperator -> { transOperator.update(ADD_TRIGGER, DateTime.now().getMillis()); transOperator.getConnection().commit(); return transOperator.getLastInsertId(); }; try { long id = dbOperator.transaction(insertAndGetLastID); t.setTriggerId((int) id); updateTrigger(t); logger.info("uploaded trigger " + t.getDescription()); } catch (SQLException ex) { <START> throw new TriggerLoaderException("trigger id is not properly created."); <END> } }</code><technical_language>consider including ex well? in previous methods</technical_language>

Target:
public synchronized void addTrigger(Trigger t) throws TriggerLoaderException { logger.info("Inserting trigger " + t.toString() + " into db."); SQLTransaction<Long> insertAndGetLastID = transOperator -> { transOperator.update(ADD_TRIGGER, DateTime.now().getMillis()); transOperator.getConnection().commit(); return transOperator.getLastInsertId(); }; try { long id = dbOperator.transaction(insertAndGetLastID); t.setTriggerId((int) id); updateTrigger(t); logger.info("uploaded trigger " + t.getDescription()); } catch (SQLException ex) { logger.error("Adding Trigger " + t.getTriggerId() + " failed." ); throw new TriggerLoaderException("trigger id is not properly created.",ex); } }
Source:
<code>void validateConfiguration() { Configuration config = request.getConfiguration(); for (String type : NOT_ALLOWED_CONFIG_TYPES) { checkArgument(!config.getProperties().containsKey(type), "Cannot change '%s' configuration in Add Service request", type); } Configuration clusterConfig = getClusterDesiredConfigs(); if (request.getRecommendationStrategy().shouldUseStackDefaults()) { <START> clusterConfig.setParentConfiguration(state.getStack().getDefaultConfig()); <END> } config.setParentConfiguration(clusterConfig); UnitUpdater.removeUnits(config); state = state.with(config); }</code><technical_language>Stack defaults for NEVER_APPLY. This is works for blueprints, too. config property explicitly. recommendation strategy is for stack advisor, stack defaults</technical_language>

Target:
void validateConfiguration() { Configuration config = request.getConfiguration(); if (strictValidation()) { for (String type : NOT_ALLOWED_CONFIG_TYPES) { CHECK.checkArgument(!config.getProperties().containsKey(type), "Cannot change '%s' configuration in Add Service request", type); } } Configuration clusterConfig = getClusterDesiredConfigs(); clusterConfig.setParentConfiguration(state.getStack().getDefaultConfig()); config.setParentConfiguration(clusterConfig); UnitUpdater.removeUnits(config, state.getStack()); state = state.with(config); }
Source:
<code>public DropwizardResourceConfig(@Nullable MetricRegistry metricRegistry) { super(); if (metricRegistry == null) { metricRegistry = new MetricRegistry(); } property(ServerProperties.WADL_FEATURE_DISABLE, Boolean.TRUE); register(loggingListener); register(new InstrumentedResourceMethodApplicationListener(metricRegistry)); register(new CacheControlledResponseFeature()); register(new io.dropwizard.jersey.guava.OptionalMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalMessageBodyWriter()); <START> register(new io.dropwizard.jersey.optional.OptionalDoubleMessageBodyWriter()); <END> register(new io.dropwizard.jersey.optional.OptionalIntMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalLongMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalParamBinder()); register(new AbstractParamConverterProvider()); register(new FuzzyEnumParamConverterProvider()); register(new SessionFactoryProvider.Binder()); if (isGuavaOnClassPath()) { register(new io.dropwizard.jersey.guava.OptionalParamBinder()); } }</code><technical_language>register instances classes forward? I thought part of issue latest Jersey longer supported registering instances</technical_language>

Target:
public DropwizardResourceConfig(@Nullable MetricRegistry metricRegistry) { super(); if (metricRegistry == null) { metricRegistry = new MetricRegistry(); } property(ServerProperties.WADL_FEATURE_DISABLE, Boolean.TRUE); register(loggingListener); register(new InstrumentedResourceMethodApplicationListener(metricRegistry)); register(new CacheControlledResponseFeature()); register(new io.dropwizard.jersey.optional.OptionalMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalDoubleMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalIntMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalLongMessageBodyWriter()); register(new io.dropwizard.jersey.optional.OptionalParamBinder()); register(new AbstractParamConverterProvider()); register(new FuzzyEnumParamConverterProvider()); register(new SessionFactoryProvider.Binder()); if (isGuavaOnClassPath()) { register(new io.dropwizard.jersey.guava.OptionalMessageBodyWriter()); register(new io.dropwizard.jersey.guava.OptionalParamBinder()); } }
Source:
<code>private void transmit(final BasicFileAttributes basicFileAttributes, final Object message) throws Exception { transmitterAction.execute(new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) { <START> HttpHeaders httpHeaders = new DefaultHttpHeaders(false); <END> MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); responseTransmitter.transmit(HttpResponseStatus.OK, responseHeaders, basicFileAttributes.size(), message); } }); }</code><technical_language>this instead of headers in constructor</technical_language>

Target:
private void transmit(final BasicFileAttributes basicFileAttributes, final Object message) throws Exception { transmitterAction.execute(new Action<ResponseTransmitter>() { @Override public void execute(ResponseTransmitter responseTransmitter) { MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(httpHeaders); responseTransmitter.transmit(HttpResponseStatus.OK, responseHeaders, basicFileAttributes.size(), message); } }); }
Source:
<code>public ControllerThread(String controllerThreadName) { super(controllerThreadName); <START> readyList = new LinkedList<>(); <END> semaphore = new Semaphore(0); }</code><technical_language>I prefer ArrayDeque LinkedList adding/removing elements middle</technical_language>

Target:
public ControllerThread(String controllerThreadName) { super(controllerThreadName); semaphore = new Semaphore(0); }
Source:
<code>private Bitmap doOCFileInBackground() { Bitmap thumbnail = null; final String imageKey = String.valueOf(((OCFile) mFile).getRemoteId()); thumbnail = getBitmapFromDiskCache(imageKey); <START> if (thumbnail == null || ((OCFile)mFile).needsUpdateThumbnail()) { <END> int px = getThumbnailDimension(); if (((OCFile)mFile).isDown()) { Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile( ((OCFile)mFile).getStoragePath(), px, px); if (bitmap != null) { thumbnail = addThumbnailToCache(imageKey, bitmap, ((OCFile)mFile).getStoragePath(), px); ((OCFile)mFile).setNeedsUpdateThumbnail(false); mStorageManager.saveFile(((OCFile)mFile)); } } else { if (mClient != null && mServerVersion != null) { OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion); if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) { try { int status = -1; String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px + Uri.encode(((OCFile)mFile).getRemotePath(), "/"); Log_OC.d("Thumbnail", "URI: " + uri); GetMethod get = new GetMethod(uri); status = mClient.executeMethod(get); if (status == HttpStatus.SC_OK) { byte[] bytes = get.getResponseBody(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px); if (thumbnail != null) { addBitmapToCache(imageKey, thumbnail); } } } catch (Exception e) { e.printStackTrace(); } } else { Log_OC.d(TAG, "Server too old"); } } } } return thumbnail; }</code><technical_language>Please, define a local OCFile variable beginning of method set (OCFile)mFile; castings free</technical_language>

Target:
private Bitmap doOCFileInBackground() { Bitmap thumbnail = null; OCFile file = (OCFile)mFile; final String imageKey = String.valueOf(file.getRemoteId()); thumbnail = getBitmapFromDiskCache(imageKey); if (thumbnail == null || file.needsUpdateThumbnail()) { int px = getThumbnailDimension(); if (file.isDown()) { Bitmap bitmap = BitmapUtils.decodeSampledBitmapFromFile( file.getStoragePath(), px, px); if (bitmap != null) { thumbnail = addThumbnailToCache(imageKey, bitmap, file.getStoragePath(), px); file.setNeedsUpdateThumbnail(false); mStorageManager.saveFile(file); } } else { if (mClient != null && mServerVersion != null) { OwnCloudVersion serverOCVersion = new OwnCloudVersion(mServerVersion); if (serverOCVersion.compareTo(new OwnCloudVersion(MINOR_SERVER_VERSION_FOR_THUMBS)) >= 0) { try { int status = -1; String uri = mClient.getBaseUri() + "/index.php/apps/files/api/v1/thumbnail/" + px + "/" + px + Uri.encode(file.getRemotePath(), "/"); Log_OC.d("Thumbnail", "URI: " + uri); GetMethod get = new GetMethod(uri); status = mClient.executeMethod(get); if (status == HttpStatus.SC_OK) { byte[] bytes = get.getResponseBody(); Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length); thumbnail = ThumbnailUtils.extractThumbnail(bitmap, px, px); if (thumbnail != null) { addBitmapToCache(imageKey, thumbnail); } } } catch (Exception e) { e.printStackTrace(); } } else { Log_OC.d(TAG, "Server too old"); } } } } return thumbnail; }
Source:
<code>private static IProject createExistingProject(final ProjectRecord record, final boolean open, IProgressMonitor monitor) throws CoreException { String projectName = record.getProjectName(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IProject project = workspace.getRoot().getProject(projectName); if (project.exists()) { if (open && !project.isOpen()) { IPath location = project.getFile( IProjectDescription.DESCRIPTION_FILE_NAME) .getLocation(); if (location != null && location.toFile().equals( record.getProjectSystemFile())) { project.open(monitor); project.refreshLocal(IResource.DEPTH_INFINITE, monitor); } } return null; } if (record.getProjectDescription() == null) { record.setProjectDescription(workspace .newProjectDescription(projectName)); IPath locationPath = new Path(record.getProjectSystemFile() .getAbsolutePath()); if (Platform.getLocation().isPrefixOf(locationPath)) record.getProjectDescription().setLocation(null); else record.getProjectDescription().setLocation(locationPath); } else record.getProjectDescription().setName(projectName); try { monitor.beginTask( UIText.WizardProjectsImportPage_CreateProjectsTask, 100); project.create(record.getProjectDescription(), SubMonitor.convert(monitor, 30)); project.open(IResource.BACKGROUND_REFRESH, <START> SubMonitor.convert(monitor, 50)); <END> return project; } finally { monitor.done(); } }</code><technical_language>here. Convert SubMonitor once, newChild()</technical_language>

Target:
private static IProject createExistingProject(final ProjectRecord record, final boolean open, IProgressMonitor monitor) throws CoreException { String projectName = record.getProjectName(); final IWorkspace workspace = ResourcesPlugin.getWorkspace(); final IProject project = workspace.getRoot().getProject(projectName); if (project.exists()) { if (open && !project.isOpen()) { SubMonitor progress = SubMonitor.convert(monitor, 2); IPath location = project.getFile( IProjectDescription.DESCRIPTION_FILE_NAME) .getLocation(); if (location != null && location.toFile().equals( record.getProjectSystemFile())) { project.open(progress.newChild(1)); project.refreshLocal(IResource.DEPTH_INFINITE, progress.newChild(1)); } } return null; } if (record.getProjectDescription() == null) { record.setProjectDescription(workspace .newProjectDescription(projectName)); IPath locationPath = new Path(record.getProjectSystemFile() .getAbsolutePath()); if (Platform.getLocation().isPrefixOf(locationPath)) record.getProjectDescription().setLocation(null); else record.getProjectDescription().setLocation(locationPath); } else { record.getProjectDescription().setName(projectName); } SubMonitor progress = SubMonitor.convert(monitor, 8); progress.setTaskName( UIText.WizardProjectsImportPage_CreateProjectsTask); project.create(record.getProjectDescription(), progress.newChild(3)); project.open(IResource.BACKGROUND_REFRESH, progress.newChild(5)); return project; }
Source:
<code>public void setPriority(final TableName tn) { int priority = HConstants.NORMAL_QOS; if (tn != null && tn.isSystemTable() <START> && !tn.equals(SlowLogTableAccessor.SLOW_LOG_TABLE_NAME)) { <END> priority = HConstants.SYSTEMTABLE_QOS; } setPriority(priority); }</code><technical_language>move this a util method some where. isMeta have. isLogTable()</technical_language>

Target:
public void setPriority(final TableName tn) { setPriority( tn != null && tn.isSystemTable() ? HConstants.SYSTEMTABLE_QOS : HConstants.NORMAL_QOS); }
Source:
<code><START> public <P extends PagedResponse<T>> Stream<P> streamByPage(String continuationToken) { <END> return (Stream<P>) pagedFlux.byPage(continuationToken).toStream(); }</code><technical_language>suggestion public <P extends PagedResponse<T>> Stream<P> streamByPage(String continuationToken) {</technical_language>

Target:
public <P extends PagedResponse<T>> Stream<P> streamByPage(String continuationToken) { return (Stream<P>) pagedFluxBase.byPage(continuationToken).toStream(); }
Source:
<code>public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { settingsMap.clear(); for (Object key : req.getParameterMap().keySet()) { String parameterName = (String) key; <START> if (!parameterName.startsWith("errorMessage") && !parameterName.equals("submit")) { <END> addStringFieldValue(settingsMap, req, parameterName); } } validateSettings(); if (fieldErrors.size() > 0) { doGetContinue(req, resp); return; } if(log.isDebugEnabled()) { for (Map.Entry<String, Object> entry : settingsMap.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); log.debug("save plugin config " + key + "=" + value + " " + value.getClass().getName()); } } pluginSettings.put(SETTINGS_MAP, settingsMap); String redirectUrl; redirectUrl = navBuilder.addons().buildRelative(); log.debug("redirect: " + redirectUrl); resp.sendRedirect(redirectUrl); }</code><technical_language>I some testing noticed customized error messages saved. I tracked this !parameterName.startsWith("errorMessage"), appears skip customized error messages. Do some background this check is here? If I remove it, header/footer settings get saved correctly. other custom error messages saved (and show in commit reject messages), get re-populated in config form for some reason</technical_language>

Target:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { settingsMap.clear(); for (Object key : req.getParameterMap().keySet()) { String parameterName = (String) key; if (!parameterName.equals("submit")) { addStringFieldValue(settingsMap, req, parameterName); } } try { validateSettings(); } catch (Exception e) { } if (fieldErrors.size() > 0) { doGetContinue(req, resp); return; } if(log.isDebugEnabled()) { for (Map.Entry<String, Object> entry : settingsMap.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); log.debug("save plugin config " + key + "=" + value + " " + value.getClass().getName()); } } pluginSettings.put(SETTINGS_MAP, settingsMap); String redirectUrl; redirectUrl = navBuilder.addons().buildRelative(); log.debug("redirect: " + redirectUrl); resp.sendRedirect(redirectUrl); }
Source:
<code>public void run(String resourceBase, String port) { <START> LOGGER.warn("DEPRECATED. Will be removed in the future. Use run(String resourceBase, JBakeConfiguration config) instead"); <END> run(resourceBase, "/", "localhost", Integer.parseInt(port)); }</code><technical_language>Minor suggestion - suggestion LOGGER.warn("DEPRECATED. This method removed in next major release. run(String resourceBase, JBakeConfiguration config) instead.");</technical_language>

Target:
public void run(String resourceBase, String port) { LOGGER.warn("DEPRECATED. This method will be removed in the next major release. Use run(String resourceBase, JBakeConfiguration config) instead."); run(resourceBase, "/", "localhost", Integer.parseInt(port)); }
Source:
<code>public long save(Experiment experiment) throws IOException { try { long id; if (experiment.getId() == ExperimentImpl.UNSAVED_ID) { String name = namingScheme.generateNameFor(experiment); experiment.setName(name); <START> ValidationResult nameValidation = namingScheme.validateName(experiment.getName()); <END> if (!nameValidation.isValid()) { throw new IOException("Cannot save Experiment - invalid name:" + nameValidation.getMessage()); } id = (Long) currentSession().save(experiment); } else { ValidationResult nameValidation = namingScheme.validateName(experiment.getName()); if (!nameValidation.isValid()) { throw new IOException("Cannot save Experiment - invalid name:" + nameValidation.getMessage()); } currentSession().update(experiment); id = experiment.getId(); } return id; } catch (MisoNamingException e) { throw new IOException("Cannot save Experiment - issue with naming scheme", e); } }</code><technical_language>Validation in service layer</technical_language>

Target:
public long save(Experiment experiment) throws IOException { long id; if (experiment.getId() == ExperimentImpl.UNSAVED_ID) { id = (Long) currentSession().save(experiment); } else { currentSession().update(experiment); id = experiment.getId(); } return id; }
Source:
<code>private void changeShip(SolGame game, Hero hero, ShipItem selected) { HullConfig newConfig = selected.getConfig(); Hull hull = hero.getHull(); Engine.Config ec = newConfig.getEngineConfig(); Engine ei = ec == null ? null : ec.example.copy(); Gun g2 = hull.getGun(true); SolShip newHero = game.getShipBuilder().build(game, hero.getPosition(), new Vector2(), hero.getAngle(), 0, hero.getPilot(), hero.getItemContainer(), newConfig, newConfig.getMaxLife(), hull.getGun(false), g2, null, ei, new ShipRepairer(), hero.getMoney(), hero.getTradeContainer(), hero.getShield(), hero.getArmor()); game.getObjMan().removeObjDelayed(hero.getHero()); game.getObjMan().addObjDelayed(newHero); <START> game.getHero().toSolShip(newHero); END> }</code><technical_language>Helps explain why, convert a // TODO: This is a hack X need fix Y :-)</technical_language>

Target:
private void changeShip(SolGame game, Hero hero, ShipItem selected) { HullConfig newConfig = selected.getConfig(); Hull hull = hero.getHull(); Engine.Config ec = newConfig.getEngineConfig(); Engine ei = ec == null ? null : ec.example.copy(); Gun g2 = hull.getGun(true); SolShip newHero = game.getShipBuilder().build(game, hero.getPosition(), new Vector2(), hero.getAngle(), 0, hero.getPilot(), hero.getItemContainer(), newConfig, newConfig.getMaxLife(), hull.getGun(false), g2, null, ei, new ShipRepairer(), hero.getMoney(), hero.getTradeContainer(), hero.getShield(), hero.getArmor()); game.getObjMan().removeObjDelayed(hero.getShip()); game.getObjMan().addObjDelayed(newHero); game.getHero().setSolShip(newHero); }
Source:
<code>public JobExecutionInfoResource getJobExecutionInfo(@PathVariable long executionId) { final JobExecution jobExecution; try { jobExecution = jobService.getJobExecution(executionId); } catch (org.springframework.batch.core.launch.NoSuchJobExecutionException e) { throw new NoSuchJobExecutionException(executionId); } final Set<String> restartableJobs = new HashSet<String>(jobLocator.getAllRestartableJobs()); final Set<String> deployedJobs = new HashSet<String>(jobLocator.getJobNames()); final Set<String> jobDefinitionNames = new HashSet<String>(getJobDefinitionNames()); final JobExecutionInfoResource jobExecutionInfoResource = jobExecutionInfoResourceAssembler.toResource(new JobExecutionInfo( jobExecution, timeZone)); final String jobName = jobExecution.getJobInstance().getJobName(); jobExecutionInfoResource.setDeleted(!jobDefinitionNames.contains(jobName)); jobExecutionInfoResource.setDeployed(deployedJobs.contains(jobName)); <START> if (restartableJobs.contains(jobName)) { <END> if (jobExecution.getStatus() != BatchStatus.COMPLETED) { jobExecutionInfoResource.setRestartable(isJobExecutionRestartable(jobExecution)); } } else { jobExecutionInfoResource.setRestartable(false); } return jobExecutionInfoResource; }</code><technical_language>In case of single JobExecution, **DistributedJobLocator**'s isRestartable(String jobName) find restartable status</technical_language>

Target:
public JobExecutionInfoResource getJobExecutionInfo(@PathVariable long executionId) { final JobExecution jobExecution; try { jobExecution = jobService.getJobExecution(executionId); } catch (org.springframework.batch.core.launch.NoSuchJobExecutionException e) { throw new NoSuchJobExecutionException(executionId); } final Set<String> restartableJobs = new HashSet<String>(jobLocator.getAllRestartableJobs()); final Set<String> deployedJobs = new HashSet<String>(jobLocator.getJobNames()); final Set<String> jobDefinitionNames = new HashSet<String>(getJobDefinitionNames()); return getJobExecutionInfoResource(jobExecution, restartableJobs, deployedJobs, jobDefinitionNames); }
Source:
<code>public void run() { StringBuilder buf = new StringBuilder("["); for (PartitionTopicInfo pti : partitionTopicInfos) { <START> buf.append(format("%s-%s-%s,", pti.topic, pti.brokerString, pti.partition)); <END> } buf.append(']'); logger.info(String.format("%s comsume at %s:%d with %s", getName(), Util.getHostFromBroker(broker), Util.getPortFromBroker(broker), buf.toString())); client = new GenClient( new ConsumerProcessor(partitionTopicInfos, Consumer.config.isBetterOrdered()), new DelegationIOConnection.DelegationIOConnectionFactory(), new DataMessageTypeFactory()); Properties prop = new Properties(); prop.setProperty("Server.host", Util.getHostFromBroker(broker)); prop.setProperty("Server.port", Util.getPortFromBroker(broker)); try { client.init(prop, getName()); } catch (ClosedChannelException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.debug("stopping fetcher " + getName() + " to broker " + broker); shutdownLatch.countDown(); }</code><technical_language>StringBuilder is used..</technical_language>

Target:
public void run() { StringBuilder buf = new StringBuilder("["); for (PartitionTopicInfo pti : partitionTopicInfos) { buf.append(pti.topic).append("-").append(pti.brokerString).append("-").append(pti.partition); } buf.append(']'); logger.info(getName() + " comsume at " + Util.getHostFromBroker(broker) + ":" + Util.getPortFromBroker(broker) + " with " + buf.toString()); client = new GenClient( new ConsumerProcessor(partitionTopicInfos, Consumer.config.isBetterOrdered()), new DelegationIOConnection.DelegationIOConnectionFactory(), new DataMessageTypeFactory()); Properties prop = new Properties(); prop.setProperty("Server.host", Util.getHostFromBroker(broker)); prop.setProperty("Server.port", Util.getPortFromBroker(broker)); try { client.init(prop, getName()); } catch (ClosedChannelException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } logger.debug("stopping fetcher " + getName() + " to broker " + broker); }
Source:
<code>protected void sendCourseRegisteredEmail(String courseId) { CourseAttributes course = logic.getCourse(courseId); EmailWrapper email = new EmailGenerator().generateUserCourseRegisterEmail( logic.getAccount(account.googleId), course); try { emailSender.sendEmail(email); } catch (EmailSendingException e) { <START> log.severe("Instructor course register email failed to send: " + TeammatesException.toStringWithStackTrace(e)); <END> } }</code><technical_language>log message changed, person reading log message this applies emails instructors, emails students. Also, this need more distinguished invitation email asking a user sign up. @damithc some suggestions this reworded (if necessary)</technical_language>

Target:
protected void sendCourseRegisteredEmail(String courseId) { CourseAttributes course = logic.getCourse(courseId); EmailWrapper email = new EmailGenerator().generateUserCourseRegisterEmail( logic.getAccount(account.googleId), course); try { emailSender.sendEmail(email); } catch (EmailSendingException e) { log.severe("User course register email failed to send: " + TeammatesException.toStringWithStackTrace(e)); } }
Source:
<code>@Override public void close(Status status, Metadata trailers) { Throwable error = null; try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } catch (Throwable e) { <START> error = e; <END> throw e; } finally { GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, error); finish(response, spanRef.getAndSet(null)); } }</code><technical_language>clear this closure server side is handled framework, error response failed. Ideally, interceptor is in a location possibility of exception is a grpc-java bug</technical_language>

Target:
@Override public void close(Status status, Metadata trailers) { GrpcServerResponse response = new GrpcServerResponse(request, status, trailers, null); finish(response, spanRef.getAndSet(null)); try (Scope scope = currentTraceContext.maybeScope(context)) { delegate().close(status, trailers); } }
Source:
<code>public String toString() { return MoreObjects.toStringHelper(this) .add("id", Integer.toHexString(System.identityHashCode(this))) .add("class", this.getClass()) <START> .add("uuid", _uuid) <END> .add("Tags", _tags) .add("VersionSetId", _versionSetId) .add("Position", _position) .toString(); }</code><technical_language>Uuid</technical_language>

Target:
public String toString() { return MoreObjects.toStringHelper(this) .add("id", Integer.toHexString(System.identityHashCode(this))) .add("class", this.getClass()) .add("Uuid", _uuid) .add("Tags", _tags) .add("VersionSetId", _versionSetId) .add("Position", _position) .toString(); }
Source:
<code>public DefaultPromise(EventExecutor executor) { this.executor = requireNonNull(executor, "executor"); <START> stage = new CompletionStageAdapter<>(this); <END> }</code><technical_language>this lazily initialized, similar in fashion Guava's [Suppliers.memoize()](<LINK_0>, thread-safety introduce performance concerns</technical_language>

Target:
public DefaultPromise(EventExecutor executor) { this.executor = requireNonNull(executor, "executor"); stage = new DefaultFutureCompletionStage<>(this); }
Source:
<code>private void processResponse(org.jgroups.Address src, byte[] buffer, int offset, int length, long requestId) { try { Response response; if (length == 0) { response = CacheNotFoundResponse.INSTANCE; } else { response = (Response) marshaller.objectFromByteBuffer(buffer, offset, length); if (response == null) { response = SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE; } } if (trace) log.tracef("%s received response for request %d from %s: %s", getAddress(), requestId, src, response); Address address = fromJGroupsAddress(src); requests.addResponse(requestId, address, response); } catch (Throwable t) { log.errorProcessingResponse(requestId, src); Exception e = t instanceof Exception ? ((Exception) t) : new CacheException(t); try { marshaller.objectFromByteBuffer(buffer, offset, length); } catch (IOException e1) { <START> e1.printStackTrace(); END> } catch (ClassNotFoundException e1) { e1.printStackTrace(); } requests.addResponse(requestId, fromJGroupsAddress(src), new ExceptionResponse(e)); } }</code><technical_language>forget TODOs</technical_language>

Target:
private void processResponse(org.jgroups.Address src, byte[] buffer, int offset, int length, long requestId) { try { Response response; if (length == 0) { response = CacheNotFoundResponse.INSTANCE; } else { response = (Response) marshaller.objectFromByteBuffer(buffer, offset, length); if (response == null) { response = SuccessfulResponse.SUCCESSFUL_EMPTY_RESPONSE; } } if (trace) log.tracef("%s received response for request %d from %s: %s", getAddress(), requestId, src, response); Address address = fromJGroupsAddress(src); requests.addResponse(requestId, address, response); } catch (Throwable t) { log.errorProcessingResponse(requestId, src); } }
Source:
<code>public void createReport(File report) throws IOException { logger.info("Writing report to " + report); int pageSize = 100; <START> Writer fw = new OutputStreamWriter(new FileOutputStream(report), "UTF-8"); <END> CSVWriter writer = new CSVWriter(fw); List<Term> output = this.outputTerms(ALATerm.TaxonomicIssue); String[] headers = output.stream().map(term -> term.toString()).collect(Collectors.toList()).toArray(new String[output.size()]); writer.writeNext(headers); for (String type: this.counts.keySet()) { String message = this.resources.getString(type); Integer count = this.counts.get(type); message = MessageFormat.format(message, count); logger.info(message); String[] values = new String[] { IssueType.COUNT.name(), type, message, Integer.toString(count) }; writer.writeNext(values); } IndexSearcher searcher = this.searcherManager.acquire(); try { Query query = new TermQuery(new org.apache.lucene.index.Term("type", ALATerm.TaxonomicIssue.qualifiedName())); TopDocs docs = searcher.search(query, pageSize); ScoreDoc last = null; while (docs.scoreDocs.length > 0) { for (ScoreDoc sd : docs.scoreDocs) { last = sd; Document doc = searcher.doc(sd.doc); String[] values = output.stream().map(term -> doc.get(this.fieldName(term))).collect(Collectors.toList()).toArray(new String[output.size()]); writer.writeNext(values); this.count("count.write.report"); } docs = searcher.searchAfter(last, query, pageSize); } } finally { this.searcherManager.release(searcher); } writer.close(); logger.info("Finished creating report"); }</code><technical_language>try-with-resources ensure this is closed</technical_language>

Target:
public void createReport(File report) throws IOException { logger.info("Writing report to " + report); int pageSize = 100; try (Writer fw = new OutputStreamWriter(new FileOutputStream(report), "UTF-8")) { CSVWriter writer = new CSVWriter(fw); List<Term> output = this.outputTerms(ALATerm.TaxonomicIssue); String[] headers = output.stream().map(term -> term.toString()).collect(Collectors.toList()).toArray(new String[output.size()]); writer.writeNext(headers); for (String type : this.counts.keySet()) { String message = this.resources.getString(type); AtomicInteger count = this.counts.getOrDefault(type, new AtomicInteger(0)); message = MessageFormat.format(message, count.intValue()); logger.info(message); String[] values = new String[]{IssueType.COUNT.name(), type, message, count.toString()}; writer.writeNext(values); } IndexSearcher searcher = this.searcherManager.acquire(); try { Query query = new TermQuery(new org.apache.lucene.index.Term("type", ALATerm.TaxonomicIssue.qualifiedName())); TopDocs docs = searcher.search(query, pageSize); ScoreDoc last = null; while (docs.scoreDocs.length > 0) { for (ScoreDoc sd : docs.scoreDocs) { last = sd; Document doc = searcher.doc(sd.doc); String[] values = output.stream().map(term -> doc.get(this.fieldName(term))).collect(Collectors.toList()).toArray(new String[output.size()]); writer.writeNext(values); this.count("count.write.report"); } docs = searcher.searchAfter(last, query, pageSize); } } finally { this.searcherManager.release(searcher); } } logger.info("Finished creating report"); }
Source:
<code>private static @NonNull ITmfTimestamp createOther(long value, int scale) { <START> return new TmfRealTimestamp(value, scale); <END> }</code><technical_language>once, inlined in create()</technical_language>

Target:
private static @NonNull ITmfTimestamp createOther(long value, int scale) { return new TmfTimestampImpl(value, scale); }
Source:
<code>public AvatarComponentObject clickEditAvatar() { showAvatarControls(); avatarEditButton.click(); <START> hideAvatarControls(); <END> return new AvatarComponentObject(driver); }</code><technical_language>add PageObjectLogging.log() in this method :)</technical_language>

Target:
public AvatarComponentObject clickEditAvatar() { showAvatarControls(); avatarEditButton.click(); hideAvatarControls(); PageObjectLogging.log("clickEditAvatar", "avatar edit button clicked", true); return new AvatarComponentObject(driver); }
Source:
<code>public boolean isTableAvailable(TableName tableName) throws IOException { <START> return listTableNames(tableName.getNameAsString()).length == 1; <END> }</code><technical_language>table_exist</technical_language>

Target:
public boolean isTableAvailable(TableName tableName) throws IOException { throw new UnsupportedOperationException("isTableAvailable"); }
Source:
<code>protected Long computeResult() { long result = 0; for (int i = 0; i < numBuckets; i += cycleSize) { if (buckets[(i + startFrom) % numBuckets] != null) { result += (buckets[(i + startFrom) % numBuckets]).longValue(); } else { <START> result += 0.0; <END> } } startFrom++; return result; }</code><technical_language>LGTM.com a warning this line: <LINK_0></technical_language>

Target:
protected Long computeResult() { long result = 0; for (int i = 0; i < numBuckets; i += cycleSize) { if (buckets[(i + startFrom) % numBuckets] != null) { result += (buckets[(i + startFrom) % numBuckets]).longValue(); } else { result += 0; } } startFrom++; return result; }
Source:
<code>public boolean hasNext() { if (parentStream.closed) { return false; } if (this.bufferedNext != null) { return true; } while (this.blobIterator.hasNext()) { BlobItem nextBlob = this.blobIterator.next(); Path nextPath = getNextListResult(nextBlob); try { <START> if (this.filter.accept(nextPath) && passesDirectoryDuplicateFilter(nextPath, nextBlob)) { <END> this.bufferedNext = nextPath; return true; } } catch (IOException e) { throw LoggingUtility.logError(logger, new DirectoryIteratorException(e)); } } return false; }</code><technical_language>nit. this called !isDuplicate</technical_language>

Target:
public boolean hasNext() { if (parentStream.closed) { return false; } if (this.bufferedNext != null) { return true; } while (this.blobIterator.hasNext()) { BlobItem nextBlob = this.blobIterator.next(); Path nextPath = getNextListResult(nextBlob); try { if (this.filter.accept(nextPath) && isNotDuplicate(nextPath, nextBlob)) { this.bufferedNext = nextPath; return true; } } catch (IOException e) { throw LoggingUtility.logError(logger, new DirectoryIteratorException(e)); } } return false; }
Source:
<code>public boolean isAPIDetailsExists(String APIId) throws APIManagementException { <START> try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); <END> PreparedStatement statement = connection .prepareStatement(SQLConstants.GET_GATEWAY_PUBLISHED_API_DETAILS)) { statement.setString(1, APIId); ResultSet rs = statement.executeQuery(); return rs.next(); } catch (SQLException e) { handleException("Failed to check API details status of API with ID " + APIId, e); } return false; }</code><technical_language>a practice a good idea call commit a connection is returned pool performing a SELECT operation. This ensures uncommitted data returned DB. pattern be, try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); connection.setAutoCommit(false); connection.commit(); PreparedStatement statement = connection.prepareStatement("SELECT ...")) { }</technical_language>

Target:
public boolean isAPIDetailsExists(String APIId) throws APIManagementException { ResultSet rs = null; try (Connection connection = GatewayArtifactsMgtDBUtil.getArtifactSynchronizerConnection(); PreparedStatement statement = connection .prepareStatement(SQLConstants.CHECK_API_EXISTS)) { connection.setAutoCommit(false); connection.commit(); statement.setString(1, APIId); rs = statement.executeQuery(); return rs.next(); } catch (SQLException e) { handleException("Failed to check API details status of API with ID " + APIId, e); } finally { GatewayArtifactsMgtDBUtil.closeResultSet(rs); } return false; }