auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private synchronized void removeSubscription() { logger.debug("Removing WeMo GENA subscription for '{}'", this); if (service.isRegistered(this)) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); String subscription = null; if (thingTypeUID.equals(THING_TYPE_INSIGHT)) { subscription = "insight1"; } else { subscription = "basicevent1"; <START> service.addSubscription(this, "basicevent1", SUBSCRIPTION_DURATION); <END> } if ((subscriptionState.get(subscription) != null) && subscriptionState.get(subscription).booleanValue()) { logger.debug("WeMo {}: Unsubscribing from service {}...", getUDN(), subscription); service.removeSubscription(this, subscription); } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } }</code><technical_language>Please remove L391 removing subscriptions here, adding</technical_language>

Target:
private synchronized void removeSubscription() { logger.debug("Removing WeMo GENA subscription for '{}'", this); if (service.isRegistered(this)) { ThingTypeUID thingTypeUID = thing.getThingTypeUID(); String subscription = null; if (thingTypeUID.equals(THING_TYPE_INSIGHT)) { subscription = "insight1"; } else { subscription = "basicevent1"; } if ((subscriptionState.get(subscription) != null) && subscriptionState.get(subscription).booleanValue()) { logger.debug("WeMo {}: Unsubscribing from service {}...", getUDN(), subscription); service.removeSubscription(this, subscription); } subscriptionState = new HashMap<String, Boolean>(); service.unregisterParticipant(this); } }
Source:
<code>public RawPacket reverseTransform( RawPacket packet) { if (absoluteSendTimeEngine .hasAbsoluteSendTimeExtension(packet) == null) { logger.warn( "RemoteBitrateEstimatorAbsSendTimeImpl: Incoming" + " packet is missing absolute send time extension!"); <START> return null; <END> } logger.info("Using RemoteBitrateEstimatorAbsSendTime: Instantiating."); incomingPacketInfo(System.currentTimeMillis(), absoluteSendTimeEngine .getAbsSendTime(packet), packet.getPayloadLength(), packet.getSSRC()); return packet; }</code><technical_language>This drops packet. This happen extension. expect wrapper handle this logic</technical_language>

Target:
public RawPacket reverseTransform( RawPacket packet) { logger.info("Using RemoteBitrateEstimatorAbsSendTime: Instantiating."); incomingPacketInfo(System.currentTimeMillis(), absoluteSendTimeEngine .getAbsSendTime(packet), packet.getPayloadLength(), packet.getSSRCAsLong()); return packet; }
Source:
<code>public void enumToStrings() throws Exception { final String expected = "CRITICAL, URGENT, HIGH, NORMAL, LOW, BACKGROUND"; <START> String actual = Utils.printEnumOptions(com.spectralogic.ds3client.models.Priority.values()); <END> assertEquals(actual, expected); }</code><technical_language>This final</technical_language>

Target:
public void enumToStrings() throws Exception { final String expected = "CRITICAL, URGENT, HIGH, NORMAL, LOW, BACKGROUND"; final String actual = Utils.printEnumOptions(com.spectralogic.ds3client.models.Priority.values()); assertEquals(actual, expected); }
Source:
<code>public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } if (this.ehcacheStateService == null) { <START> throw new ServerMisconfigurationException("Server failed to retrieve EhcacheStateService ."); <END> } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }</code><technical_language>throw AssertionError in constructor for this - if happens, is serious</technical_language>

Target:
public EhcacheEntityResponse invoke(ClientDescriptor clientDescriptor, EhcacheEntityMessage message) { try { if (this.offHeapResourceIdentifiers.isEmpty()) { throw new ServerMisconfigurationException("Server started without any offheap resources defined." + " Check your server configuration and define at least one offheap resource."); } switch (message.getType()) { case LIFECYCLE_OP: return invokeLifeCycleOperation(clientDescriptor, (LifecycleMessage) message); case SERVER_STORE_OP: return invokeServerStoreOperation(clientDescriptor, (ServerStoreOpMessage) message); default: throw new IllegalMessageException("Unknown message : " + message); } } catch (ClusterException e) { return responseFactory.failure(e); } catch (Exception e) { LOGGER.error("Unexpected exception raised during operation: " + message, e); return responseFactory.failure(new InvalidOperationException(e)); } }
Source:
<code>protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered SSORestApiLogoutServlet"); String token = request.getParameter("token"); String scope = request.getParameter("scope"); Map<String, Object> revokeResponse = SSOOAuthServiceUtils.revoke(token, scope); String error = (String) revokeResponse.get("error"); if (StringUtils.isNotEmpty(error)) { log.error("Unable to logout user: {}", error); } try (OutputStream os = response.getOutputStream()) { ObjectMapper mapper = new ObjectMapper().configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false) <START> .enableDefaultTyping(ObjectMapper.DefaultTyping.OBJECT_AND_NON_CONCRETE); <END> String jsonPayload = mapper.writeValueAsString(revokeResponse); response.setContentType("application/json"); byte[] jsonPayloadBytes = jsonPayload.getBytes(StandardCharsets.UTF_8.name()); response.setContentLength(jsonPayloadBytes.length); os.write(jsonPayloadBytes); log.trace("Sending json data {}", jsonPayload); } log.debug("Exiting SSORestApiLogoutServlet"); }</code><technical_language>reason JsonObjectSerializer in SSOOAuthServiceUtils</technical_language>

Target:
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { log.debug("Entered SSORestApiLogoutServlet"); String token = request.getParameter("token"); String scope = request.getParameter("scope"); Map<String, Object> revokeResponse = SSOOAuthServiceUtils.revoke(token, scope); String error = (String) revokeResponse.get("error"); if (StringUtils.isNotEmpty(error)) { log.error("Unable to logout user: {}", error); } try (OutputStream os = response.getOutputStream()) { String jsonPayload = new JsonObjectSerializer().serialize(revokeResponse); response.setContentType("application/json"); byte[] jsonPayloadBytes = jsonPayload.getBytes(StandardCharsets.UTF_8.name()); response.setContentLength(jsonPayloadBytes.length); os.write(jsonPayloadBytes); log.trace("Sending json data {}", jsonPayload); } log.debug("Exiting SSORestApiLogoutServlet"); }
Source:
<code>public void waitForInitialData_resilientInCaseOfRetries() throws InterruptedException { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); final SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); Random randomizer = new Random(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { Realm realm = null; try { <START> realm = Realm.getInstance(config); <END> } catch (DownloadingRealmInterruptedException ignored) { assertFalse(new File(config.getPath()).exists()); } finally { if (realm != null) { realm.close(); Realm.deleteRealm(config); } } } }); t.start(); SystemClock.sleep(randomizer.nextInt(5)); t.interrupt(); t.join(); } }</code><technical_language>i is call Thread.currentThread().interrupt() here. long downloading latch is latch getInstance() reaches, throw there. need loop 10 times</technical_language>

Target:
public void waitForInitialData_resilientInCaseOfRetries() throws InterruptedException { SyncCredentials credentials = SyncCredentials.usernamePassword(UUID.randomUUID().toString(), "password", true); SyncUser user = SyncUser.login(credentials, Constants.AUTH_URL); final SyncConfiguration config = new SyncConfiguration.Builder(user, Constants.USER_REALM) .waitForInitialRemoteData() .build(); for (int i = 0; i < 10; i++) { Thread t = new Thread(new Runnable() { @Override public void run() { Realm realm = null; try { Thread.currentThread().interrupt(); realm = Realm.getInstance(config); } catch (DownloadingRealmInterruptedException ignored) { assertFalse(new File(config.getPath()).exists()); } finally { if (realm != null) { realm.close(); Realm.deleteRealm(config); } } } }); t.start(); t.join(); } }
Source:
<code><START> private boolean hasNewIncomingFile(final Contentlet contentletIn) throws DotContentletStateException{ <END> try { final String identifierStr = contentletIn.getIdentifier(); if(!UtilMethods.isSet(identifierStr)){ return true; } final Identifier identifier = APILocator.getIdentifierAPI().find(identifierStr); final File incomingFile = contentletIn.getBinary(FileAssetAPI.BINARY_FIELD); String incomingFileName = null != incomingFile ? incomingFile.getName() : StringPool.BLANK; if(UtilMethods.isSet(contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD))){ incomingFileName = contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD); } return !incomingFileName.equals(identifier.getAssetName()); } catch (Exception e) { throw new DotContentletStateException("Exception trying to determine if there's a new incoming file.",e); } }</code><technical_language>this method signature a FileAsset a contentlet check baseType insure is a FileAsset</technical_language>

Target:
private boolean hasNewIncomingFile(final Contentlet contentletIn) throws DotContentletStateException{ if(!contentletIn.isFileAsset()){ throw new IllegalArgumentException("Contentlet isn't a subtype of FileAsset"); } try { final String identifierStr = contentletIn.getIdentifier(); if(!UtilMethods.isSet(identifierStr)){ return true; } final Identifier identifier = APILocator.getIdentifierAPI().find(identifierStr); final File incomingFile = contentletIn.getBinary(FileAssetAPI.BINARY_FIELD); String incomingFileName = null != incomingFile ? incomingFile.getName() : StringPool.BLANK; if(UtilMethods.isSet(contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD))){ incomingFileName = contentletIn.getStringProperty(FileAssetAPI.FILE_NAME_FIELD); } return !incomingFileName.equals(identifier.getAssetName()); } catch (Exception e) { throw new DotContentletStateException("Exception trying to determine if there's a new incoming file.",e); } }
Source:
<code>public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer) throws InterruptedException { this.responder = responder; ServerBootstrap bootstrap = new ServerBootstrap().group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class).childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { if (initializer != null) { initializer.accept(ch); } ch.pipeline().addLast("frameDecoder", new NettyFrameDecoder()) .addLast("frameEncoder", new NettyFrameEncoder()).addLast("handler", new NettyServerAvroHandler()); } <START> }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true); <END> serverChannel = bootstrap.bind(addr).sync().channel(); }</code><technical_language>option(ChannelOption.SO_BACKLOG, 1024) I 128 is enough, set 1024. .childOption(ChannelOption.TCP_NODELAY, true) Nagle algorithm is disabled client side, I set server side</technical_language>

Target:
public NettyServer(Responder responder, InetSocketAddress addr, final Consumer<SocketChannel> initializer) throws InterruptedException { this(responder, addr, initializer, null, null, null, null); }
Source:
<code>public void onMatch(RelOptRuleCall call) { final HiveFilter topFilter = call.rel(0); final HiveFilter bottomFilter = call.rel(1); <START> RexBuilder rexBuilder = topFilter.getCluster().getRexBuilder(); RexProgram bottomProgram = createProgram(bottomFilter); RexProgram topProgram = createProgram(topFilter); RexProgram mergedProgram = RexProgramBuilder.mergePrograms( topProgram, bottomProgram, rexBuilder); RexNode newCondition = expandLocalRef(rexBuilder, mergedProgram.getCondition(), mergedProgram.getExprList()); final RelBuilder relBuilder = call.builder(); relBuilder.push(bottomFilter.getInput()) .filter(newCondition); <END> call.transformTo(relBuilder.build()); }</code><technical_language>I impression replace this code with: final RelBuilder relBuilder = call.builder(); relBuilder.push(bottomFilter.getInput()) .filter(topFilter.getCondition(), bottomFilter.getCondition()); If I remember well, is a simplification builder.filter(...) takes cares of flattening</technical_language>

Target:
public void onMatch(RelOptRuleCall call) { final HiveFilter topFilter = call.rel(0); final HiveFilter bottomFilter = call.rel(1); final RelBuilder relBuilder = call.builder(); relBuilder.push(bottomFilter.getInput()) .filter(bottomFilter.getCondition(), topFilter.getCondition()); call.transformTo(relBuilder.build()); }
Source:
<code>void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { <START> opChain.latch.await(); <END> synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.containsKey(partitionId) ? partitionCount.get(partitionId) : 0; partitionCount.put(partitionId, count + 1); } } double blobBalanceThreshold = 3.0 * Math.ceil(blobsPut / (double) clusterMap.getWritablePartitionIds().size()); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } }</code><technical_language>@vgkholla a good point is good put a timeout in await(), do risk test run forever. like: if(opChain.latch.await(!1000, TimeUnit.MILLISECONDS) { // create some exception here. }</technical_language>

Target:
void checkOperationChains(List<OperationChain> opChains) throws Exception { Map<PartitionId, Integer> partitionCount = new HashMap<>(); double blobsPut = 0; for (OperationChain opChain : opChains) { if (!opChain.latch.await(AWAIT_TIMEOUT, TimeUnit.SECONDS)) { Assert.fail("Timeout waiting for operation chain " + opChain.chainId + " to finish."); } synchronized (opChain.testFutures) { for (TestFuture testFuture : opChain.testFutures) { testFuture.check(); } } if (opChain.blobId != null) { blobsPut++; PartitionId partitionId = new BlobId(opChain.blobId, clusterMap).getPartition(); int count = partitionCount.containsKey(partitionId) ? partitionCount.get(partitionId) : 0; partitionCount.put(partitionId, count + 1); } } double numPartitions = clusterMap.getWritablePartitionIds().size(); if (opChains.size() > numPartitions) { double blobBalanceThreshold = BALANCE_FACTOR * Math.ceil(blobsPut / numPartitions); for (Map.Entry<PartitionId, Integer> entry : partitionCount.entrySet()) { Assert.assertTrue("Number of blobs is " + entry.getValue() + " on partition: " + entry.getKey() + ", which is greater than the threshold of " + blobBalanceThreshold, entry.getValue() <= blobBalanceThreshold); } } }
Source:
<code>protected void validateUserPasswordAndUpdateIfNeeded(String newPassword, UserVO user, String currentPassword) { if (newPassword == null) { s_logger.trace("No new password to update for user: " + user.getUuid()); return; } if (StringUtils.isBlank(newPassword)) { throw new InvalidParameterValueException("Password cannot be empty or blank."); } Account callingAccount = getCurrentCallingAccount(); boolean isRootAdminExecutingPasswordUpdate = callingAccount.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(callingAccount.getId()); boolean isDomainAdmin = isDomainAdmin(callingAccount.getId()); boolean isAdmin = isDomainAdmin || isRootAdminExecutingPasswordUpdate; if (isAdmin) { s_logger.trace(String.format("Admin account [uuid=%s] executing password update for user [%s] ", callingAccount.getUuid(), user.getUuid())); } if (!isAdmin && StringUtils.isBlank(currentPassword)) { <START> throw new InvalidParameterValueException("You must inform the current password when updating a user password."); <END> } if (CollectionUtils.isEmpty(_userPasswordEncoders)) { throw new CloudRuntimeException("No user authenticators configured!"); } if (!isAdmin) { validateCurrentPassword(user, currentPassword); } UserAuthenticator userAuthenticator = _userPasswordEncoders.get(0); String newPasswordEncoded = userAuthenticator.encode(newPassword); user.setPassword(newPasswordEncoded); }</code><technical_language>"To set a new password current password provided."</technical_language>

Target:
protected void validateUserPasswordAndUpdateIfNeeded(String newPassword, UserVO user, String currentPassword) { if (newPassword == null) { s_logger.trace("No new password to update for user: " + user.getUuid()); return; } if (StringUtils.isBlank(newPassword)) { throw new InvalidParameterValueException("Password cannot be empty or blank."); } Account callingAccount = getCurrentCallingAccount(); boolean isRootAdminExecutingPasswordUpdate = callingAccount.getId() == Account.ACCOUNT_ID_SYSTEM || isRootAdmin(callingAccount.getId()); boolean isDomainAdmin = isDomainAdmin(callingAccount.getId()); boolean isAdmin = isDomainAdmin || isRootAdminExecutingPasswordUpdate; if (isAdmin) { s_logger.trace(String.format("Admin account [uuid=%s] executing password update for user [%s] ", callingAccount.getUuid(), user.getUuid())); } if (!isAdmin && StringUtils.isBlank(currentPassword)) { throw new InvalidParameterValueException("To set a new password the current password must be provided."); } if (CollectionUtils.isEmpty(_userPasswordEncoders)) { throw new CloudRuntimeException("No user authenticators configured!"); } if (!isAdmin) { validateCurrentPassword(user, currentPassword); } UserAuthenticator userAuthenticator = _userPasswordEncoders.get(0); String newPasswordEncoded = userAuthenticator.encode(newPassword); user.setPassword(newPasswordEncoded); }
Source:
<code>public Integer getTo() { if (to == null) { return null; } else <START> return this.to; <END> }</code><technical_language>return to; is enough</technical_language>

Target:
public Integer getTo() { return this.to; }
Source:
<code>public void setUp() { <START> assertUpdate("CREATE TABLE nation_partitioned(nationkey BIGINT, name VARCHAR, comment VARCHAR, regionkey BIGINT) WITH (partitioned_by = ARRAY['regionkey'])"); <END> assertUpdate("CREATE TABLE orders(orderkey BIGINT, totalprice BIGINT, categoryid BIGINT) WITH (partitioned_by = ARRAY['categoryid'])"); assertUpdate("INSERT INTO nation_partitioned SELECT nationkey, name, comment, regionkey from tpch.tiny.nation", 25); }</code><technical_language>do need this table? partitioned nation</technical_language>

Target:
public void setUp() { assertUpdate("CREATE TABLE nation_partitioned(nationkey BIGINT, name VARCHAR, comment VARCHAR, regionkey BIGINT) WITH (partitioned_by = ARRAY['regionkey'])"); assertUpdate("INSERT INTO nation_partitioned SELECT nationkey, name, comment, regionkey from tpch.tiny.nation", 25); assertUpdate("CREATE TABLE region(regionkey BIGINT, name VARCHAR, comment VARCHAR)"); assertUpdate("CREATE TABLE orders(orderkey BIGINT, custkey BIGINT, totalprice DOUBLE, orderdate DATE, " + "orderpriority VARCHAR, clerk VARCHAR, shippriority VARCHAR, comment VARCHAR, orderstatus VARCHAR)"); }
Source:
<code>public boolean canPerform(ApprovalCategory.Id actionId, short level) { boolean projectLevel = projectControl.canPerform(actionId, level); Collection<RefRight> refRights = getRefRights(); final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; for (final RefRight right : refRights) { if (right.getApprovalCategoryId().equals(actionId) && groups.contains(right.getAccountGroupId()) && matches(refName, right.getRefPattern())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } boolean refLevel = (val >= level); <START> return projectLevel || refLevel; <END> }</code><technical_language>remarks in FunctionState, a question project rules if ref rules for this category matching this ref</technical_language>

Target:
public boolean canPerform(ApprovalCategory.Id actionId, short level) { boolean projectLevel = projectControl.canPerform(actionId, level); Collection<RefRight> refRights = getRefRights(); final Set<AccountGroup.Id> groups = getCurrentUser().getEffectiveGroups(); int val = Integer.MIN_VALUE; for (final RefRight right : refRights) { if (right.getApprovalCategoryId().equals(actionId) && groups.contains(right.getAccountGroupId()) && matches(refName, right.getRefPattern())) { if (val < 0 && right.getMaxValue() > 0) { val = right.getMaxValue(); } else { val = Math.max(right.getMaxValue(), val); } } } if (val == Integer.MIN_VALUE) { return val >= level; } else { return projectLevel; } }
Source:
<code>private Map<String, Object> largeMessageConf() { Map<String, Object> conf = basicConf(); <START> conf.put(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE, 1024000); <END> return conf; }</code><technical_language>this 102400, test-large-msg defines</technical_language>

Target:
private Map<String, Object> largeMessageConf() { Map<String, Object> conf = basicConf(); conf.put(Config.STORM_MESSAGING_NETTY_BUFFER_SIZE, 102_400); return conf; }
Source:
<code>public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForInstructor( String feedbackSessionName, String courseId, String feedbackQuestionId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); if (fsa == null) { throw new EntityDoesNotExistException( <START> ERROR_GET_NON_EXISTENT_SESSION); <END> } InstructorAttributes instructor = instructorsLogic.getInstructorForEmail(courseId, userEmail); Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); FeedbackQuestionAttributes question = fqLogic.getFeedbackQuestion(feedbackQuestionId); InstructorAttributes instructorGiver = instructor; StudentAttributes studentGiver = null; updateBundleAndRecipientListWithResponsesForInstructor(courseId, userEmail, fsa, instructor, bundle, recipientList, question, instructorGiver, studentGiver); return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }</code><technical_language>This too. Do combine other thrown exceptions in rest of changed code line applicable (if characters do exceed 110 char limit)</technical_language>

Target:
public FeedbackSessionQuestionsBundle getFeedbackSessionQuestionsForInstructor( String feedbackSessionName, String courseId, String feedbackQuestionId, String userEmail) throws EntityDoesNotExistException { FeedbackSessionAttributes fsa = fsDb.getFeedbackSession( courseId, feedbackSessionName); if (fsa == null) { throw new EntityDoesNotExistException(ERROR_NON_EXISTENT_FS_GET + courseId + "/" + feedbackSessionName); } InstructorAttributes instructor = instructorsLogic.getInstructorForEmail(courseId, userEmail); Map<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>> bundle = new HashMap<FeedbackQuestionAttributes, List<FeedbackResponseAttributes>>(); Map<String, Map<String, String>> recipientList = new HashMap<String, Map<String, String>>(); FeedbackQuestionAttributes question = fqLogic.getFeedbackQuestion(feedbackQuestionId); InstructorAttributes instructorGiver = instructor; StudentAttributes studentGiver = null; updateBundleAndRecipientListWithResponsesForInstructor(courseId, userEmail, fsa, instructor, bundle, recipientList, question, instructorGiver, studentGiver); return new FeedbackSessionQuestionsBundle(fsa, bundle, recipientList); }
Source:
<code>public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer = new OnePassDataIndexer(); Map<String, String> params = new HashMap<>(); params.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); params.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); <START> indexer.init(params); <END> indexer.index(eventStream); return trainModel(iterations, indexer, cutoff); }</code><technical_language>indexer get access report map, add counters configuration settings</technical_language>

Target:
public GISModel trainModel(ObjectStream<Event> eventStream, int iterations, int cutoff) throws IOException { DataIndexer indexer = new OnePassDataIndexer(); TrainingParameters indexingParameters = new TrainingParameters(); indexingParameters.put(GIS.CUTOFF_PARAM, Integer.toString(cutoff)); indexingParameters.put(GIS.ITERATIONS_PARAM, Integer.toString(iterations)); reportMap = new HashMap<>(); indexer.init(indexingParameters,reportMap); indexer.index(eventStream); return trainModel(iterations, indexer); }
Source:
<code><START> public synchronized void stopIt() { <END> stop = true; }</code><technical_language>do this synchronized? IMHO stopped times wish</technical_language>

Target:
public void stopIt() { stop = true; }
Source:
<code>public Template resolveTemplate(String templateName) { if (wikiBaseUrl != null) { int indexOf = templateName.indexOf(':'); if (indexOf == 0) { templateName = templateName.substring(1); } else if (indexOf == -1) { templateName = "Template:" + templateName; } URL url = computeRawUrl(templateName); if (url != null) { try { Reader input = <START> createInputReader(url); <END> try { String content = readFully(input); Template template = new Template(); String basicName = templateName.toLowerCase().startsWith("template:") ? templateName.substring(templateName.lastIndexOf(':') + 1) : templateName; template.setName(basicName); template.setTemplateMarkup(content); return template; } finally { input.close(); } } catch (final IOException e) { final String message = MessageFormat.format("Cannot read from {0}: {1}", url, e.getMessage()); Logger.getLogger(WikiTemplateResolver.class.getName()).log(Level.WARNING, message, e); } } } return null; }</code><technical_language>consider replacing this Guava: Resources.toString(url, StandardCharsets.UTF_8)</technical_language>

Target:
public Template resolveTemplate(String templateName) { if (wikiBaseUrl != null) { int indexOf = templateName.indexOf(':'); if (indexOf == 0) { templateName = templateName.substring(1); } else if (indexOf == -1) { templateName = "Template:" + templateName; } URL url = computeRawUrl(templateName); if (url != null) { try { String content = readContent(url); Template template = new Template(); String basicName = templateName.toLowerCase().startsWith("template:") ? templateName.substring(templateName.lastIndexOf(':') + 1) : templateName; template.setName(basicName); template.setTemplateMarkup(content); return template; } catch (final IOException e) { final String message = MessageFormat.format("Cannot read from {0}: {1}", url, e.getMessage()); Logger.getLogger(WikiTemplateResolver.class.getName()).log(Level.WARNING, message, e); } } } return null; }
Source:
<code>public void init() { Assert.hasText(nextUri, "nextUri cannot be null or empty."); Assert.hasText(logoutUri, "logoutUri cannot be null or empty."); <START> Assert.hasText(resendVerificationUri, "resendVerificationUri cannot be null or empty."); <END> Assert.notNull(client, "client cannot be null."); Assert.notNull(eventPublisher, "eventPublisher cannot be null."); }</code><technical_language>Assert.hasText(sendVerificationEmailUri, "sendVerificationEmailUri null empty.");</technical_language>

Target:
public void init() { Assert.hasText(nextUri, "nextUri cannot be null or empty."); Assert.hasText(logoutUri, "logoutUri cannot be null or empty."); Assert.hasText(sendVerificationEmailUri, "sendVerificationEmailUri cannot be null or empty."); Assert.notNull(client, "client cannot be null."); Assert.notNull(eventPublisher, "eventPublisher cannot be null."); }
Source:
<code>protected void populateElements(Object inputElement) { <START> final Object[] convertedInputElement = ((List<?>) inputElement).toArray(); <END> for (int i = 0; i < convertedInputElement.length; i++) { if (convertedInputElement[i] instanceof Variable) { final Variable variable = (Variable) convertedInputElement[i]; final IPath path = variable.getPath().makeAbsolute(); variable.setPath(path); registerElement(path, convertedInputElement[i]); } } setShowRoot(false); for (final IPath additionalPath : fAdditionalPaths) { registerPath(additionalPath); } }</code><technical_language>do this is a list</technical_language>

Target:
protected void populateElements(Object inputElement) { if (inputElement instanceof List<?>) { final Object[] convertedInputElement = ((List<?>) inputElement).toArray(); for (int i = 0; i < convertedInputElement.length; i++) { if (convertedInputElement[i] instanceof Variable) { final Variable variable = (Variable) convertedInputElement[i]; final IPath path = variable.getPath().makeAbsolute(); variable.setPath(path); registerElement(path, convertedInputElement[i]); } } } setShowRoot(false); for (final IPath additionalPath : fAdditionalPaths) { registerPath(additionalPath); } }
Source:
<code>public List<Map<String, String>> taskConfigs(int maxTasks) { String query = config.getString(JdbcSourceConnectorConfig.QUERY_CONFIG); List<Map<String, String>> taskConfigs; if (!query.isEmpty()) { <START> taskConfigs = new ArrayList<>(1); <END> Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, ""); taskConfigs.add(taskProps); } else { List<String> currentTables = tableMonitorThread.tables(); if (currentTables.isEmpty()) { taskConfigs = new ArrayList<>(); log.warn("No tasks are running because no tables were found"); } else { int numGroups = Math.min(currentTables.size(), maxTasks); List<List<String>> tablesGrouped = ConnectorUtils.groupPartitions(currentTables, numGroups); taskConfigs = new ArrayList<>(tablesGrouped.size()); for (List<String> taskTables : tablesGrouped) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, StringUtils.join(taskTables, ",")); taskConfigs.add(taskProps); } } } return taskConfigs; }</code><technical_language>Nit: replace this line taskConfigs.add(taskProps) line a single call Collections.singletonList(...)</technical_language>

Target:
public List<Map<String, String>> taskConfigs(int maxTasks) { String query = config.getString(JdbcSourceConnectorConfig.QUERY_CONFIG); List<Map<String, String>> taskConfigs; if (!query.isEmpty()) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, ""); taskConfigs = Collections.singletonList(taskProps); } else { List<String> currentTables = tableMonitorThread.tables(); if (currentTables.isEmpty()) { taskConfigs = Collections.emptyList(); log.warn("No tasks will be run because no tables were found"); } else { int numGroups = Math.min(currentTables.size(), maxTasks); List<List<String>> tablesGrouped = ConnectorUtils.groupPartitions(currentTables, numGroups); taskConfigs = new ArrayList<>(tablesGrouped.size()); for (List<String> taskTables : tablesGrouped) { Map<String, String> taskProps = new HashMap<>(configProperties); taskProps.put(JdbcSourceTaskConfig.TABLES_CONFIG, StringUtils.join(taskTables, ",")); taskConfigs.add(taskProps); } } } return taskConfigs; }
Source:
<code>static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) { info = update(info, msg, session); switch (msg.kind) { case VOID: return empty(info); case ROWS: Responses.Result.Rows r = (Responses.Result.Rows)msg; ColumnDefinitions columnDefs; if (r.metadata.columns == null) { assert statement instanceof BoundStatement; columnDefs = ((BoundStatement)statement).statement.getPreparedId().resultSetMetadata; assert columnDefs != null; } else { columnDefs = r.metadata.columns; } Token.Factory tokenFactory = (session == null) ? null : session.getCluster().manager.metadata.tokenFactory(); assert r.metadata.pagingState == null || info != null; <START> CodecRegistry codecRegistry = (session == null) <END> ? CodecRegistry.DEFAULT_INSTANCE : session.getCluster().getConfiguration().getCodecRegistry(); return r.metadata.pagingState == null ? new SinglePage(columnDefs, tokenFactory, protocolVersion, codecRegistry, r.data, info) : new MultiPage(columnDefs, tokenFactory, protocolVersion, codecRegistry, r.data, info, r.metadata.pagingState, session, statement); case SET_KEYSPACE: case SCHEMA_CHANGE: return empty(info); case PREPARED: throw new RuntimeException("Prepared statement received when a ResultSet was expected"); default: logger.error("Received unknown result type '{}'; returning empty result set", msg.kind); return empty(info); } }</code><technical_language>JAVA-996, this replaced columnDefs.codecRegistry - is null</technical_language>

Target:
static ArrayBackedResultSet fromMessage(Responses.Result msg, SessionManager session, ProtocolVersion protocolVersion, ExecutionInfo info, Statement statement) { info = update(info, msg, session); switch (msg.kind) { case VOID: return empty(info); case ROWS: Responses.Result.Rows r = (Responses.Result.Rows)msg; ColumnDefinitions columnDefs; if (r.metadata.columns == null) { assert statement instanceof BoundStatement; columnDefs = ((BoundStatement)statement).statement.getPreparedId().resultSetMetadata; assert columnDefs != null; } else { columnDefs = r.metadata.columns; } Token.Factory tokenFactory = (session == null) ? null : session.getCluster().manager.metadata.tokenFactory(); assert r.metadata.pagingState == null || info != null; return r.metadata.pagingState == null ? new SinglePage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info) : new MultiPage(columnDefs, tokenFactory, protocolVersion, columnDefs.codecRegistry, r.data, info, r.metadata.pagingState, session, statement); case SET_KEYSPACE: case SCHEMA_CHANGE: return empty(info); case PREPARED: throw new RuntimeException("Prepared statement received when a ResultSet was expected"); default: logger.error("Received unknown result type '{}'; returning empty result set", msg.kind); return empty(info); } }
Source:
<code>private static void updateConnection(final Connection connection, final MagnetManager.Magnets magnets, final com.ait.lienzo.client.core.types.Point2D abeLocation, final Consumer<Boolean> isAutoConnectionConsumer, final Consumer<WiresMagnet> magnetConsumer) { final WiresMagnet[] magnet = new WiresMagnet[]{null}; final boolean[] auto = new boolean[]{false}; if (null != connection) { <START> final Optional<DiscreteConnection> discreteConnection = connection instanceof DiscreteConnection ? <END> Optional.of((DiscreteConnection) connection) : Optional.empty(); discreteConnection .ifPresent(c -> { c.getMagnetIndex().ifPresent(index -> magnet[0] = magnets.getMagnet(index)); auto[0] = c.isAuto(); }); if (null == magnet[0]) { magnet[0] = getMagnetForConnection(connection, magnets, abeLocation); discreteConnection.ifPresent(c -> c.setIndex(magnet[0].getIndex())); } } isAutoConnectionConsumer.accept(auto[0]); magnetConsumer.accept(magnet[0]); }</code><technical_language>Personally, I find this abuse of Optional.. a ternary comparison set Optional is in ways depending isPresent() not.. IMO a simple if... else block easier eyes! This is opinion though.. wrong people in ways :-)</technical_language>

Target:
private static void updateConnection(final Connection connection, final MagnetManager.Magnets magnets, final com.ait.lienzo.client.core.types.Point2D abeLocation, final Consumer<Boolean> isAutoConnectionConsumer, final Consumer<WiresMagnet> magnetConsumer) { final WiresMagnet[] magnet = new WiresMagnet[]{null}; final boolean[] auto = new boolean[]{false}; if (null != connection) { final DiscreteConnection dc = connection instanceof DiscreteConnection ? (DiscreteConnection) connection : null; if (null != dc) { dc.getMagnetIndex().ifPresent(index -> magnet[0] = magnets.getMagnet(index)); auto[0] = dc.isAuto(); } if (null == magnet[0]) { magnet[0] = getMagnetForConnection(connection, magnets, abeLocation); if (null != dc) { dc.setIndex(magnet[0].getIndex()); } } } isAutoConnectionConsumer.accept(auto[0]); magnetConsumer.accept(magnet[0]); }
Source:
<code>public String generateCredData(String nextNonce) { MessageDigest digest; String usrPwdNonceHash = null; String nonce; try { nonce = new String(Base64.decodeBase64(nextNonce), "utf-8"); digest = MessageDigest.getInstance("MD5"); String usrPwd = Constants.PROVIDER_ID + ":" + Constants.SERVER_SECRET; String usrPwdHash = Base64.encodeBase64String(digest.digest(usrPwd.getBytes("utf-8"))); String usrPwdNonce = usrPwdHash + ":" + nonce; usrPwdNonceHash = Base64.encodeBase64String(digest.digest(usrPwdNonce.getBytes("utf-8"))); } catch (Exception e) { String msg = "Problem occurred in generating server credentials."; <START> log.error(msg, e); <END> } return usrPwdNonceHash; }</code><technical_language>Avoid catching generic exceptions. If some multiple exceptions thrown need handled way, multi-catch blocks.. Also, a good idea re-throw exception wrapped in checked exception well</technical_language>

Target:
public String generateCredData(String nextNonce) { MessageDigest digest; String usrPwdNonceHash = null; String nonce; try { nonce = new String(Base64.decodeBase64(nextNonce), "utf-8"); digest = MessageDigest.getInstance("MD5"); String usrPwd = Constants.PROVIDER_ID + ":" + Constants.SERVER_SECRET; String usrPwdHash = Base64.encodeBase64String(digest.digest(usrPwd.getBytes("utf-8"))); String usrPwdNonce = usrPwdHash + ":" + nonce; usrPwdNonceHash = Base64.encodeBase64String(digest.digest(usrPwdNonce.getBytes("utf-8"))); } catch (UnsupportedEncodingException e) { String msg = "Problem occurred in encoding credentials data."; log.error(msg, e); } catch (NoSuchAlgorithmException e) { String msg = "Problem occurred in generating password hash."; log.error(msg, e); } return usrPwdNonceHash; }
Source:
<code>private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) { Map<Node,Computer> computers = getComputerMap(); Computer c; c = byNameMap.get(n.getNodeName()); if (c!=null) { c.setNode(n); } else { <START> if((n.getNumExecutors()>0 && bypass(FeatureSwitchConfiguration.Feature.DEFER_EXECUTOR_CREATION,n.isAcceptingTasks())) <END> || n==Jenkins.getInstance()) { computers.put(n, c = n.createComputer()); if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) { RetentionStrategy retentionStrategy = c.getRetentionStrategy(); if (retentionStrategy != null) { retentionStrategy.start(c); } else { c.connect(true); } } } } if(c!=null){ used.add(c); } }</code><technical_language>if bypass a method of enum need import static FeatureSwitchConfiguration.Feature.DEFER_EXECUTOR_CREATION.isOffOr(n.isAcceptingTasks()) reads bypass</technical_language>

Target:
private void updateComputer(Node n, Map<String,Computer> byNameMap, Set<Computer> used, boolean automaticSlaveLaunch) { Map<Node,Computer> computers = getComputerMap(); Computer c; c = byNameMap.get(n.getNodeName()); if (c!=null) { c.setNode(n); } else { if((n.getNumExecutors()>0 && Feature.DEFER_EXECUTOR_CREATION.isOffOr(n.isAcceptingTasks())) || n==Jenkins.getInstance()) { computers.put(n, c = n.createComputer()); if (!n.isHoldOffLaunchUntilSave() && automaticSlaveLaunch) { RetentionStrategy retentionStrategy = c.getRetentionStrategy(); if (retentionStrategy != null) { retentionStrategy.start(c); } else { c.connect(true); } } } } if(c!=null){ used.add(c); } }
Source:
<code>public long getTotalConnectionCount() { <START> return totalConnectionCount; <END> }</code><technical_language>return sum instead</technical_language>

Target:
public long getTotalConnectionCount() { return statsPerHost .values() .stream() .mapToLong(HostStats::getHostConnectionCount) .sum(); }
Source:
<code>public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> nodes = getSelectedNodes(event); RepositoryTreeNode node = nodes.get(0); WizardDialog wizardDialog = null; try { switch (node.getType()) { case REF: Ref ref = (Ref) node.getObject(); wizardDialog = new PushBranchDialog(getShell(event), new PushBranchWizard(node.getRepository(), ref)); break; case TAG: wizardDialog = new WizardDialog(getShell(event), createPushTagsWizard(nodes)); break; case REPO: wizardDialog = new WizardDialog(getShell(event), new PushWizard(node.getRepository())); break; default: throw new UnsupportedOperationException("type not supported!"); } } catch (URISyntaxException e1) { Activator.handleError(e1.getMessage(), e1, true); return null; } <START> wizardDialog.open(); <END> return null; }</code><technical_language>happened setHelpAvailable()? started pages, set contexts PushWizard pages. work appears incomplete, wizard isHelpAvailable set... removing setHelpAvailable() is a step backwards. If wants pick this incomplete work, undo changes again</technical_language>

Target:
public Object execute(ExecutionEvent event) throws ExecutionException { List<RepositoryTreeNode> nodes = getSelectedNodes(event); RepositoryTreeNode node = nodes.get(0); WizardDialog wizardDialog = null; try { switch (node.getType()) { case REF: Ref ref = (Ref) node.getObject(); wizardDialog = new PushBranchDialog(getShell(event), new PushBranchWizard(node.getRepository(), ref)); break; case TAG: wizardDialog = new WizardDialog(getShell(event), createPushTagsWizard(nodes)); break; case REPO: wizardDialog = new WizardDialog(getShell(event), new PushWizard(node.getRepository())); break; default: throw new UnsupportedOperationException("type not supported!"); } } catch (URISyntaxException e1) { Activator.handleError(e1.getMessage(), e1, true); return null; } wizardDialog.setHelpAvailable(true); wizardDialog.open(); return null; }
Source:
<code>public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String schemeName = request.getParameter("schemeName"); final String schemeId = request.getParameter("schemeId"); final String schemeDescription = request.getParameter("schemeDescription"); final boolean schemeArchived = (request.getParameter("schemeArchived") != null) ? Boolean.parseBoolean(request.getParameter("schemeArchived")) : false; final WorkflowSchemeForm schemeForm = new WorkflowSchemeForm.Builder().schemeName(schemeName) .schemeDescription(schemeDescription) .schemeArchived(schemeArchived) .build(); try { final User user = this.userWebAPI.getUser(request); final WorkflowHelper helper = WorkflowHelper.getInstance(); <START> String x = saveScheme(schemeId, schemeForm, user); <END> response.getWriter().println(x); } catch (Exception e) { Logger.error(this.getClass(), e.getMessage(), e); writeError(response, e.getMessage()); } }</code><technical_language>More descriptive var name</technical_language>

Target:
public void save(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { final String schemeName = request.getParameter("schemeName"); final String schemeId = request.getParameter("schemeId"); final String schemeDescription = request.getParameter("schemeDescription"); final boolean schemeArchived = (request.getParameter("schemeArchived") != null) ? Boolean.parseBoolean(request.getParameter("schemeArchived")) : false; final WorkflowSchemeForm schemeForm = new WorkflowSchemeForm.Builder().schemeName(schemeName) .schemeDescription(schemeDescription) .schemeArchived(schemeArchived) .build(); try { final User user = this.userWebAPI.getUser(request); final WorkflowHelper helper = WorkflowHelper.getInstance(); String responseMessage = saveScheme(schemeId, schemeForm, user); response.getWriter().println(responseMessage); } catch (Exception e) { Logger.error(this.getClass(), e.getMessage(), e); writeError(response, e.getMessage()); } }
Source:
<code>public String sanitizeHashStr(final String raw) throws InvalidHashException { if (!raw.matches("^[a-zA-Z0-9]*$")) { throw new InvalidHashException( String.format("Hash %s has invalid characters. Should be only alphanumeric.", raw)); <START> } else if (this.type.equals("MD5") && raw.length() != 32) { <END> throw new InvalidHashException( String.format("MD5 hash %s has incorrect length %d, expected 32", raw, raw.length())); } else if (this.type.equals("SHA1") && raw.length() != 40) { throw new InvalidHashException( String.format("SHA1 hash %s has incorrect length %d, expected 40", raw, raw.length())); } return raw.toLowerCase(); }</code><technical_language>nitpick: "MD5" a final constant variable instead, 32 a constant well? code a easier read. e.g. private final static int MD5_EXPECTED_LENGTH = 32 something</technical_language>

Target:
public String sanitizeHashStr(final String raw) throws InvalidHashException { if (this == HashUtils.MD5 && raw.length() != MD5_SIZE_BYTES) { throw new InvalidHashException( String.format("MD5 hash %s has incorrect length %d, expected %d", raw, raw.length(), MD5_SIZE_BYTES)); } else if (this == HashUtils.SHA1 && raw.length() != SHA1_SIZE_BYTES) { throw new InvalidHashException( String.format("SHA1 hash %s has incorrect length %d, expected %d", raw, raw.length(), SHA1_SIZE_BYTES)); } else if (!raw.matches("^[a-zA-Z0-9]*$")) { throw new InvalidHashException( String.format("Hash %s has invalid characters. Should be only alphanumeric.", raw)); } return raw.toLowerCase(); }
Source:
<code>private boolean isGuavaPrecondition(Symbol.MethodSymbol symbol) { return symbol.owner().type().is("com.google.common.base.Preconditions") <START> && ("checkNotNull".equals(symbol.name()) || "checkArgument".equals(symbol.name()) || "checkState".equals(symbol.name()) ); <END> }</code><technical_language>symbol.name() called 3 times? worth a dedicated variable</technical_language>

Target:
private boolean isGuavaPrecondition(Symbol.MethodSymbol symbol) { String name = symbol.name(); return symbol.owner().type().is("com.google.common.base.Preconditions") && ("checkNotNull".equals(name) || "checkArgument".equals(name) || "checkState".equals(name) ); }
Source:
<code>protected AbstractLightblueClientCRUDController getControllerInstance() { if (controller == null) { try { <START> if (removeHooks == Boolean.TRUE) <END> controller = new ArtificialLightblueClientCRUDController(httpServerPort); else if(removeHooks == Boolean.FALSE) controller = new ArtificialLightblueClientCRUDControllerWithHooks(httpServerPort); } catch (Exception e) { throw new RuntimeException("Unable to create test CRUD Controller", e); } } return controller; }</code><technical_language>removeHooks is Boolean, is boolean. if(removeHooks) { .. } else { ... } is sufficient</technical_language>

Target:
protected AbstractLightblueClientCRUDController getControllerInstance() { if (controller == null) { try { if (removeHooks) controller = new ArtificialLightblueClientCRUDController(httpServerPort); else controller = new ArtificialLightblueClientCRUDControllerWithHooks(httpServerPort); } catch (Exception e) { throw new RuntimeException("Unable to create test CRUD Controller", e); } } return controller; }