auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>private Ds3ClientHelpers.Job buildRestoreJob(final Ds3ClientHelpers helper) throws IOException, CommandException { if (!this.pipe && !this.sync && Guard.isNullOrEmpty(this.prefixes)) { return helper.startReadAllJob(this.bucketName, ReadJobOptions.create().withPriority(this.priority)); } <START> final Iterable<Ds3Object>objects = helper.toDs3Iterable(getObjects(helper), FolderNameFilter.filter());; <END> return helper.startReadJob(this.bucketName, objects, ReadJobOptions.create().withPriority(this.priority)); }</code><technical_language>is extra semicolon this line</technical_language>

Target:
private Ds3ClientHelpers.Job buildRestoreJob(final Ds3ClientHelpers helper) throws IOException, CommandException { if (!this.pipe && !this.sync && Guard.isNullOrEmpty(this.prefixes)) { return helper.startReadAllJob(this.bucketName, ReadJobOptions.create().withPriority(this.priority)); } final Iterable<Ds3Object>objects = helper.toDs3Iterable(getObjects(helper), FolderNameFilter.filter()); return helper.startReadJob(this.bucketName, objects, ReadJobOptions.create().withPriority(this.priority)); }
Source:
<code>protected static void appendAttributes(Map<String, Object> parameters, Object config, String prefix) { if (config == null) { return; } Method[] methods = config.getClass().getMethods(); for (Method method : methods) { try { Parameter parameter = method.getAnnotation(Parameter.class); <START> if (parameter == null || !parameter.attribute()) <END> continue; String name = method.getName(); if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { String key; if (parameter.key().length() > 0) { key = parameter.key(); } else { int i = name.startsWith("get") ? 3 : 2; key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); } Object value = method.invoke(config); if (value != null) { if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; } parameters.put(key, value); } } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } }</code><technical_language>pls. {...}</technical_language>

Target:
protected static void appendAttributes(Map<String, Object> parameters, Object config, String prefix) { if (config == null) { return; } Method[] methods = config.getClass().getMethods(); for (Method method : methods) { try { Parameter parameter = method.getAnnotation(Parameter.class); if (parameter == null || !parameter.attribute()) { continue; } String name = method.getName(); if ((name.startsWith("get") || name.startsWith("is")) && !"getClass".equals(name) && Modifier.isPublic(method.getModifiers()) && method.getParameterTypes().length == 0 && isPrimitive(method.getReturnType())) { String key; if (parameter.key().length() > 0) { key = parameter.key(); } else { int i = name.startsWith("get") ? 3 : 2; key = name.substring(i, i + 1).toLowerCase() + name.substring(i + 1); } Object value = method.invoke(config); if (value != null) { if (prefix != null && prefix.length() > 0) { key = prefix + "." + key; } parameters.put(key, value); } } } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } } }
Source:
<code>public void createNameFirstWordsHashBucketMatcher() { AffOrgMatcher matcher = FirstWordsHashBucketMatcherFactory.createNameFirstWordsHashBucketMatcher(); AffOrgJoiner joiner = getInternalState(matcher, AffOrgJoiner.class); assertTrue(joiner instanceof AffOrgHashBucketJoiner); BucketHasher<AffMatchAffiliation> affHasher = getInternalState(joiner, "affiliationBucketHasher"); assertTrue(affHasher instanceof AffiliationOrgNameBucketHasher); assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); BucketHasher<AffMatchOrganization> orgHasher = getInternalState(joiner, "organizationBucketHasher"); assertTrue(orgHasher instanceof OrganizationNameBucketHasher); <START> assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); <END> AffOrgMatchComputer computer = getInternalState(matcher, AffOrgMatchComputer.class); List<AffOrgMatchVoter> voters = getInternalState(computer, "affOrgMatchVoters"); assertNameFirstWordsHashBucketMatcherVoters(voters); }</code><technical_language>check orgHasher instead of affHasher</technical_language>

Target:
public void createNameFirstWordsHashBucketMatcher() { AffOrgMatcher matcher = FirstWordsHashBucketMatcherFactory.createNameFirstWordsHashBucketMatcher(); AffOrgJoiner joiner = getInternalState(matcher, AffOrgJoiner.class); assertTrue(joiner instanceof AffOrgHashBucketJoiner); BucketHasher<AffMatchAffiliation> affHasher = getInternalState(joiner, "affiliationBucketHasher"); assertTrue(affHasher instanceof AffiliationOrgNameBucketHasher); assertInternalStringPartFirstLettersHasher(affHasher, 2, 2); BucketHasher<AffMatchOrganization> orgHasher = getInternalState(joiner, "organizationBucketHasher"); assertTrue(orgHasher instanceof OrganizationNameBucketHasher); assertInternalStringPartFirstLettersHasher(orgHasher, 2, 2); AffOrgMatchComputer computer = getInternalState(matcher, AffOrgMatchComputer.class); List<AffOrgMatchVoter> voters = getInternalState(computer, "affOrgMatchVoters"); assertNameFirstWordsHashBucketMatcherVoters(voters); }
Source:
<code>public FormValidation doCheckProjects(@AncestorInPath Job<?,?> project, @QueryParameter String value ) { if(!project.hasPermission(Item.CONFIGURE)){ return FormValidation.ok(); } StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isBlank(projectName)) { <START> return FormValidation.error(Messages.BuildTrigger_NoSuchProject(" ", "?")); <END> } Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if(item==null){ Item nearest = Items.findNearest(Job.class, projectName, Jenkins.getInstance()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof Job) || !(item instanceof ParameterizedJobMixIn.ParameterizedJob)) { return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); } Authentication auth = Tasks.getAuthenticationOf((ParameterizedJobMixIn.ParameterizedJob)project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }</code><technical_language>I return another warning ("Blank job name in list")</technical_language>

Target:
public FormValidation doCheckProjects(@AncestorInPath Job<?,?> project, @QueryParameter String value ) { if(!project.hasPermission(Item.CONFIGURE)){ return FormValidation.ok(); } StringTokenizer tokens = new StringTokenizer(Util.fixNull(value),","); boolean hasProjects = false; while(tokens.hasMoreTokens()) { String projectName = tokens.nextToken().trim(); if (StringUtils.isBlank(projectName)) { return FormValidation.error("Blank project name in the list"); } Item item = Jenkins.getInstance().getItem(projectName,project,Item.class); if(item==null){ Item nearest = Items.findNearest(Job.class, projectName, Jenkins.getInstance()); String alternative = nearest != null ? nearest.getRelativeNameFrom(project) : "?"; return FormValidation.error(Messages.BuildTrigger_NoSuchProject(projectName, alternative)); } if(!(item instanceof Job) || !(item instanceof ParameterizedJobMixIn.ParameterizedJob)) { return FormValidation.error(Messages.BuildTrigger_NotBuildable(projectName)); } Authentication auth = Tasks.getAuthenticationOf((ParameterizedJobMixIn.ParameterizedJob)project); if (auth.equals(ACL.SYSTEM) && !QueueItemAuthenticatorConfiguration.get().getAuthenticators().isEmpty()) { auth = Jenkins.ANONYMOUS; } if (!item.getACL().hasPermission(auth, Item.BUILD)) { return FormValidation.error(Messages.BuildTrigger_you_have_no_permission_to_build_(projectName)); } hasProjects = true; } if (!hasProjects) { return FormValidation.error(Messages.BuildTrigger_NoProjectSpecified()); } return FormValidation.ok(); }
Source:
<code>public void visitToken(DetailAST ast) { final String commentContent = JavadocUtil.getBlockCommentContent(ast); if (JavadocUtil.isJavadocComment(commentContent)) { final String[] commentLines = MATCH_COMMENT_SEPARATOR.split(commentContent); for (int i = 0; i < commentLines.length - 1; i++) { final String comment = commentLines[i]; <START> if (CommonUtil.isBlank(comment) || comment.trim().charAt(0) != '*') { <END> log(ast, MSG_MISSING_ASTERISK); } } } }</code><technical_language>Interesting. Ok, lets char comparison</technical_language>

Target:
public void visitToken(DetailAST ast) { final String commentContent = JavadocUtil.getBlockCommentContent(ast); if (JavadocUtil.isJavadocComment(commentContent)) { final String[] commentLines = MATCH_COMMENT_SEPARATOR.split(commentContent); for (int i = 0; i < commentLines.length - 1; i++) { final String commentLine = commentLines[i]; if (!isValidLine(commentLine)) { log(ast, MSG_MISSING_ASTERISK); } } final String lastCommentLine = commentLines[commentLines.length - 1]; if (!CommonUtil.isBlank(lastCommentLine) && lastCommentLine.trim().charAt(0) != '*') { log(ast, MSG_MISSING_ASTERISK); } } }
Source:
<code>public ImmutableSpongeBrewingStandData(Integer value) { super(ImmutableBrewingStandData.class, value, Keys.REMAINING_BREW_TIME); this.immutableValue = SpongeValueBuilder.boundedBuilder(Keys.REMAINING_BREW_TIME) <START> .maximum(0).maximum(Integer.MAX_VALUE).defaultValue(0).actualValue(this.getValue()) <END> .build().asImmutable(); }</code><technical_language>defaut 400, in Vanilla</technical_language>

Target:
public ImmutableSpongeBrewingStandData(Integer value) { super(ImmutableBrewingStandData.class, value, Keys.REMAINING_BREW_TIME); }
Source:
<code>private boolean filter(Position position) { <START> if (allowAlarms && position.getAttributes().containsKey(Position.KEY_ALARM)) { <END> return false; } StringBuilder filterType = new StringBuilder(); Position last = null; if (Context.getIdentityManager() != null) { last = Context.getIdentityManager().getLastPosition(position.getDeviceId()); } if (filterInvalid(position)) { filterType.append("Invalid "); } if (filterZero(position)) { filterType.append("Zero "); } if (filterDuplicate(position, last)) { filterType.append("Duplicate "); } if (filterFuture(position)) { filterType.append("Future "); } if (filterApproximate(position)) { filterType.append("Approximate "); } if (filterStatic(position)) { filterType.append("Static "); } if (filterDistance(position, last)) { filterType.append("Distance "); } if (filterMaxSpeed(position, last)) { filterType.append("MaxSpeed "); } if (filterType.length() > 0 && !filterLimit(position, last)) { StringBuilder message = new StringBuilder(); message.append("Position filtered by "); message.append(filterType.toString()); message.append("filters from device: "); message.append(Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId()); message.append(" with id: "); message.append(position.getDeviceId()); Log.info(message.toString()); return true; } return false; }</code><technical_language>please move filterLimit check beginning well</technical_language>

Target:
private boolean filter(Position position) { StringBuilder filterType = new StringBuilder(); Position last = null; if (Context.getIdentityManager() != null) { last = Context.getIdentityManager().getLastPosition(position.getDeviceId()); } if (skipLimit(position, last) || skipAlarms(position)) { return false; } if (filterInvalid(position)) { filterType.append("Invalid "); } if (filterZero(position)) { filterType.append("Zero "); } if (filterDuplicate(position, last)) { filterType.append("Duplicate "); } if (filterFuture(position)) { filterType.append("Future "); } if (filterApproximate(position)) { filterType.append("Approximate "); } if (filterStatic(position)) { filterType.append("Static "); } if (filterDistance(position, last)) { filterType.append("Distance "); } if (filterMaxSpeed(position, last)) { filterType.append("MaxSpeed "); } if (filterType.length() > 0) { StringBuilder message = new StringBuilder(); message.append("Position filtered by "); message.append(filterType.toString()); message.append("filters from device: "); message.append(Context.getIdentityManager().getById(position.getDeviceId()).getUniqueId()); message.append(" with id: "); message.append(position.getDeviceId()); Log.info(message.toString()); return true; } return false; }
Source:
<code><START> public void stop() throws Exception { <END> if (started) { server.stop(); serverThread.join(); started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderSelector.close(); curatorFramework.getConnectionStateListenable().removeListener(this); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }</code><technical_language>this is unrelated this issue, this stop method synchronized</technical_language>

Target:
public synchronized void stop() throws Exception { if (started) { server.stop(); serverThread.join(); started = false; currentLeader = null; if (curatorFramework.getState().equals(CuratorFrameworkState.STARTED)) { pathChildrenCache.getListenable().removeListener(this); pathChildrenCache.close(); leaderSelector.close(); curatorFramework.getConnectionStateListenable().removeListener(this); curatorFramework.close(); } log.info("Oracle server has been stopped."); } }
Source:
<code>public void testCreateRegionWithMinAndSize() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> size = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> expectedMax = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(4, 4, 4), new Vector3i(11, 9, 7)); for (int i = 0; i < mins.size(); ++i) { <START> BlockRegion region = new BlockRegion().union(mins.get(i)).setSize(size.get(i)); <END> assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(size.get(i), region.getSize(new Vector3i())); assertEquals(expectedMax.get(i), region.getMax(new Vector3i())); } }</code><technical_language>Do union() set min value. setMin() instead. suggestion BlockRegion region = new BlockRegion().setMin(mins.get(i)).setSize(size.get(i));</technical_language>

Target:
public void testCreateRegionWithMinAndSize() { List<Vector3i> mins = Arrays.asList(new Vector3i(), new Vector3i(1, 1, 1), new Vector3i(3, 4, 5)); List<Vector3i> size = Arrays.asList(new Vector3i(1, 1, 1), new Vector3i(3, 3, 3), new Vector3i(8, 5, 2)); List<Vector3i> expectedMax = Arrays.asList(new Vector3i(), new Vector3i(3, 3, 3), new Vector3i(10, 8, 6)); for (int i = 0; i < mins.size(); ++i) { BlockRegion region = new BlockRegion().setMin(mins.get(i)).setSize(size.get(i)); assertEquals(mins.get(i), region.getMin(new Vector3i())); assertEquals(size.get(i), region.getSize(new Vector3i())); assertEquals(expectedMax.get(i), region.getMax(new Vector3i())); } }
Source:
<code>private void getRandomReadingListPage() { ReadingListPageDao.instance().randomPage(new CallbackTask.Callback<PageTitle>() { @Override public void success(@Nullable PageTitle title) { <START> setProgress(false); <END> if (getCallback() != null) { if (title != null) { getCallback().onSelectPage(new HistoryEntry(title, HistoryEntry.SOURCE_FEED_RANDOM)); } else { getCallback().onError(new RuntimeException(getString(R.string.view_random_card_error))); } } } }); }</code><technical_language>Minor: a bit cleaner do this in onError callback fork calling getRandomReadingListPage. In a sense I guess technically more correct do this disk I/O completes I surprised if difference human-perceptible</technical_language>

Target:
private void getRandomReadingListPage() { ReadingListPageDao.instance().randomPage(new CallbackTask.Callback<PageTitle>() { @Override public void success(@Nullable PageTitle title) { if (getCallback() != null) { if (title != null) { getCallback().onSelectPage(new HistoryEntry(title, HistoryEntry.SOURCE_FEED_RANDOM)); } else { getCallback().onError(new RuntimeException(getString(R.string.view_random_card_error))); } } } }); }
Source:
<code>public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Pushwoosh.getInstance().registerForPushNotifications(result -> { if (result.isSuccess()) { Log.d(TAG, "Successfully registered for push notifications with token: " + result.getData()); } else { if (result.getException() != null) { <START> Log.d(TAG, "Failed to register for push notifications:u " <END> + result.getException().getMessage()); } } }); } }</code><technical_language>nit: extra u in logging message</technical_language>

Target:
public void onReceive(Context context, Intent intent) { if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) { Pushwoosh.getInstance().registerForPushNotifications(result -> { if (result.isSuccess()) { Log.d(TAG, "Successfully registered for push notifications with token: " + result.getData()); } else { if (result.getException() != null) { Log.d(TAG, "Failed to register for push notifications: " + result.getException().getMessage()); } } }); } }
Source:
<code>public void startGroup() { if (DEBUG_ENABLED) { ++indent; } <START> if (DEBUG_ENABLED) { <END> log("<!-- start group -->"); } delegate.startGroup(); }</code><technical_language>@lw-lin, some if statements combined. Please check code next of review for these</technical_language>

Target:
public void startGroup() { ++indent; log("<!-- start group -->"); delegate.startGroup(); }
Source:
<code>public void sendSMSMessage(StudyIdentifier studyId, Phone phone, String message) { checkNotNull(studyId); checkNotNull(phone); checkNotNull(message); if (message.length() > BridgeConstants.SMS_CHARACTER_LIMIT) { throw new BridgeServiceException("SMS message cannot be longer than 140 UTF-8/ASCII characters."); <START> } <END> Map<String, MessageAttributeValue> smsAttributes = Maps.newHashMap(); smsAttributes.put(SENDER_ID, attribute("Bridge")); smsAttributes.put(SMS_TYPE, attribute(SMS_TYPE_TRANSACTIONAL)); PublishResult result = snsClient.publish(new PublishRequest() .withMessage(message) .withPhoneNumber(phone.getNumber()) .withMessageAttributes(smsAttributes)); LOG.debug("Sent SMS message, study=" + studyId.getIdentifier() + ", message ID=" + result.getMessageId()); }</code><technical_language>Do limit is bytes characters? If want count bytes, do message.getBytes(Charsets.UTF-whatever).length. Do encoding SMS sends message with</technical_language>

Target:
public void sendSMSMessage(StudyIdentifier studyId, Phone phone, String message) { checkNotNull(studyId); checkNotNull(phone); checkNotNull(message); if (message.getBytes(Charset.forName("US-ASCII")).length > BridgeConstants.SMS_CHARACTER_LIMIT) { throw new BridgeServiceException("SMS message cannot be longer than 140 UTF-8/ASCII characters."); } Map<String, MessageAttributeValue> smsAttributes = Maps.newHashMap(); smsAttributes.put(SENDER_ID, attribute("Bridge")); smsAttributes.put(SMS_TYPE, attribute(SMS_TYPE_TRANSACTIONAL)); PublishResult result = snsClient.publish(new PublishRequest() .withMessage(message) .withPhoneNumber(phone.getNumber()) .withMessageAttributes(smsAttributes)); LOG.debug("Sent SMS message, study=" + studyId.getIdentifier() + ", message ID=" + result.getMessageId()); }
Source:
<code>public void setupTest() { EXTERNAL_ID.setHealthCode(null); <START> EXTERNAL_ID.setSubstudyId(null); <END> dao = new DynamoExternalIdDao(); dao.setMapper(mapper); dao.setGetExternalIdRateLimiter(rateLimiter); }</code><technical_language>modifying constants for tests. If need modify them, member variables re-initialize test</technical_language>

Target:
public void setupTest() { externalId = ExternalIdentifier.create(TEST_STUDY, ID); dao = new DynamoExternalIdDao(); dao.setMapper(mapper); dao.setGetExternalIdRateLimiter(rateLimiter); }
Source:
<code>public CounterStateProvider(ITmfTrace trace) { super(trace, CounterAnalysis.ID); <START> ImmutableSet.Builder<CounterAspect> counterAspects = new Builder<>(); Iterable<@NonNull ITmfEventAspect<?>> aspects = trace.getEventAspects(); for (ITmfEventAspect<?> aspect : aspects) { if (aspect instanceof CounterAspect) { counterAspects.add((CounterAspect) aspect); } } fCounterAspects = counterAspects.build(); <END> }</code><technical_language>ImmutableSet.copyOf(Iterables.filter(...))</technical_language>

Target:
public CounterStateProvider(ITmfTrace trace) { super(trace, CounterAnalysis.ID); Iterable<ITmfEventAspect<?>> counterAspects = Iterables.filter(trace.getEventAspects(), aspect -> aspect instanceof CounterAspect); fCounterAspects = ImmutableSet.copyOf(counterAspects); }
Source:
<code>public int getRowCount() { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount - ONLY REPORTS THE CURRENT NUMBER OF ROWS RETRIEVED"); synchronized (rowsLock) { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount before"); if (wasrowspopulated) return rows.size(); else <START> return -1; <END> } }</code><technical_language>clear caller expects/handles a -1, please confirm</technical_language>

Target:
public int getRowCount() { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount - ONLY REPORTS THE CURRENT NUMBER OF ROWS RETRIEVED"); synchronized (rowsLock) { HPCCJDBCUtils.traceoutln(Level.WARNING, "HPCCResultSet getRowCount before"); if (wasRowsObjPopulated) return rows.size(); else return InvalidRowCount; } }
Source:
<code>public int hashCode() { <START> return new HashCodeBuilder(17, 37).append(owner).append(created).append(failed).toHashCode(); <END> }</code><technical_language>a shorter Objects.hash(owner, created, failed); here</technical_language>

Target:
public int hashCode() { return Objects.hash(owner, created, failed); }
Source:
<code>public int getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += path.length() * Character.BYTES; result += sizeOfObjectArray(blocks.size()); for (InternalHiveBlock block : blocks) { result += block.getEstimatedSizeInBytes(); } int numBuckets = 1; if (partitionInfo.getBucketConversion().isPresent()) { numBuckets = partitionInfo.getBucketConversion().get().getPartitionBucketCount(); } <START> result += partitionInfo.getEstimatedSizeInBytes() / numBuckets; <END> return result; }</code><technical_language>nit: for safe ? ;)</technical_language>

Target:
public int getEstimatedSizeInBytes() { int result = INSTANCE_SIZE; result += relativeUri.length; result += blockEndOffsets.length * Long.BYTES; result += sizeOfObjectArray(blockAddresses.size()); for (List<HostAddress> addresses : blockAddresses) { result += sizeOfObjectArray(addresses.size()); for (HostAddress address : addresses) { result += HOST_ADDRESS_INSTANCE_SIZE + address.getHostText().length() * Character.BYTES; } } return result; }
Source:
<code>public AdColonyAdOptions getAdOptionsFromAdConfig(MediationAdConfiguration adConfiguration) { AdColonyAdOptions adColonyAdOptions = null; <START> if (adConfiguration.getMediationExtras() != null) { <END> adColonyAdOptions = getAdOptionsFromExtras(adConfiguration.getMediationExtras()); } String bidResponse = adConfiguration.getBidResponse(); if (bidResponse != null && !bidResponse.equals("")) { if (adColonyAdOptions == null) { adColonyAdOptions = new AdColonyAdOptions(); } adColonyAdOptions.setOption(KEY_ADCOLONY_BID_RESPONSE, bidResponse); } return adColonyAdOptions; }</code><technical_language>getAdOptionsFromExtras() handle a nullable extras, returns a nonnull AdColonyAdOptions. call here, need do a null check adColonyAdOptions below</technical_language>

Target:
public AdColonyAdOptions getAdOptionsFromAdConfig(MediationAdConfiguration adConfiguration) { AdColonyAdOptions adColonyAdOptions = getAdOptionsFromExtras(adConfiguration.getMediationExtras()); String bidResponse = adConfiguration.getBidResponse(); if (bidResponse != null && !bidResponse.equals("")) { adColonyAdOptions.setOption(KEY_ADCOLONY_BID_RESPONSE, bidResponse); } return adColonyAdOptions; }
Source:
<code>private OffsetResponse getLatestOffsetResponse(SimpleConsumer consumer, Map<TopicAndPartition, PartitionOffsetRequestInfo> offsetInfo, JobContext context) { for (int i = 0; i <= FETCH_FROM_LEADER_MAX_RETRIES; i++) { try { OffsetResponse offsetResponse = consumer.getOffsetsBefore(new OffsetRequest(offsetInfo, kafka.api.OffsetRequest.CurrentVersion(), CamusJob.getKafkaClientName(context))); if (offsetResponse == null || offsetResponse.hasError()) { throw new RuntimeException(); } return offsetResponse; <START> } catch (RuntimeException e) { <END> log.warn("Fetching offset from leader " + consumer.host() + ":" + consumer.port() + " has failed " + (i + 1) + " time(s). " + (FETCH_FROM_LEADER_MAX_RETRIES - i) + " retries left."); } } return null; }</code><technical_language>Kafka exception is RuntimeException</technical_language>

Target:
private OffsetResponse getLatestOffsetResponse(SimpleConsumer consumer, Map<TopicAndPartition, PartitionOffsetRequestInfo> offsetInfo, JobContext context) { for (int i = 0; i < NUM_TRIES_FETCH_FROM_LEADER; i++) { try { OffsetResponse offsetResponse = consumer.getOffsetsBefore(new OffsetRequest(offsetInfo, kafka.api.OffsetRequest.CurrentVersion(), CamusJob.getKafkaClientName(context))); if (offsetResponse.hasError()) { throw new RuntimeException("offsetReponse has error."); } return offsetResponse; } catch (Exception e) { log.warn("Fetching offset from leader " + consumer.host() + ":" + consumer.port() + " has failed " + (i + 1) + " time(s). Reason: " + e.getMessage() + " " + (NUM_TRIES_FETCH_FROM_LEADER - i - 1) + " retries left."); if (i < NUM_TRIES_FETCH_FROM_LEADER - 1) { try { Thread.sleep((long)(Math.random() * (i + 1) * 1000)); } catch (InterruptedException e1) { log.error("Caught interrupted exception between retries of getting latest offsets. " + e1.getMessage()); } } } } return null; }
Source:
<code>public String exportFile(HttpServletRequest req, HttpServletResponse response) { String fileName = this.userLabelPrinting.getFilenameDL(); if (fileName.indexOf(".pdf") != -1) { response.setContentType("application/pdf"); } else { response.setContentType("application/vnd.ms-excel"); } String encodedFilename = FileUtils.encodeFilenameForDownload(fileName); final String userAgent = req.getHeader("User-Agent"); if (userAgent.indexOf("MSIE") != -1 || userAgent.indexOf("Trident") != -1) { response.setHeader("Content-disposition", "attachment; filename=\"" + encodedFilename + "\";"); } else { response.setHeader("Content-disposition", "attachment; filename=\"" + encodedFilename + "\"; filename*=\"UTF-8''" + encodedFilename + "\";"); } <START> <END> response.setCharacterEncoding("UTF-8"); File xls = new File(this.userLabelPrinting.getFilenameDLLocation()); FileInputStream in; try { in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[LabelPrintingController.BUFFER_SIZE]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } catch (FileNotFoundException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } catch (IOException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } return ""; }</code><technical_language>Setting response header duplicated in files. Please pull this out a common method in a utility class</technical_language>

Target:
public String exportFile(HttpServletRequest req, HttpServletResponse response) { String fileName = this.userLabelPrinting.getFilenameDL(); if (fileName.indexOf(".pdf") != -1) { response.setContentType("application/pdf"); } else { response.setContentType("application/vnd.ms-excel"); } FieldbookUtil.resolveContentDisposition(fileName, response, req.getHeader("User-Agent")); response.setCharacterEncoding("UTF-8"); File xls = new File(this.userLabelPrinting.getFilenameDLLocation()); FileInputStream in; try { in = new FileInputStream(xls); OutputStream out = response.getOutputStream(); byte[] buffer = new byte[LabelPrintingController.BUFFER_SIZE]; int length = 0; while ((length = in.read(buffer)) > 0) { out.write(buffer, 0, length); } in.close(); out.close(); } catch (FileNotFoundException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } catch (IOException e) { LabelPrintingController.LOG.error(e.getMessage(), e); } return ""; }
Source:
<code>public void testJobQueueAddingJobsOneByOne() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder() .setWorkflowId(queueName) .setParallelJobs(1) <START> .setJobPurgeInterval(-1); <END> _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); _driver.enqueueJob(queueName, "JOB0", jobBuilder); for (int i = 1; i < 5; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (i - 1)), 10000L, TaskState.COMPLETED); _driver.waitToStop(queueName, 5000L); _driver.enqueueJob(queueName, "JOB" + i, jobBuilder); _driver.resume(queueName); } _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }</code><technical_language>discussed offline, if this method overwriting configs, this is fine me</technical_language>

Target:
public void testJobQueueAddingJobsOneByOne() throws InterruptedException { String queueName = TestHelper.getTestMethodName(); JobQueue.Builder builder = TaskTestUtil.buildJobQueue(queueName); WorkflowConfig.Builder workflowCfgBuilder = new WorkflowConfig.Builder().setWorkflowId(queueName).setParallelJobs(1); _driver.start(builder.setWorkflowConfig(workflowCfgBuilder.build()).build()); JobConfig.Builder jobBuilder = new JobConfig.Builder().setTargetResource(WorkflowGenerator.DEFAULT_TGT_DB) .setCommand(MockTask.TASK_COMMAND).setMaxAttemptsPerTask(2); _driver.enqueueJob(queueName, "JOB0", jobBuilder); for (int i = 1; i < 5; i++) { _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + (i - 1)), 10000L, TaskState.COMPLETED); _driver.waitToStop(queueName, 5000L); _driver.enqueueJob(queueName, "JOB" + i, jobBuilder); _driver.resume(queueName); } _driver.pollForJobState(queueName, TaskUtil.getNamespacedJobName(queueName, "JOB" + 4), TaskState.COMPLETED); }
Source:
<code>public void multi_filter() { control = 0; server.configure(routes -> routes. get("/", "NOT FILTERED"). get("/other", "OTHER"). filter((uri, context, nextFilter) -> { control += 5; <START> System.out.println("I'm a basic LOGGING filter"); <END> return nextFilter.get(); }) .filter((uri, context, nextFilter) -> { control *= 3; if ("/".equals(uri)) { return new Payload("text/html", "FILTERED"); } return nextFilter.get(); })); control = 0; get("/other").produces("OTHER"); Assert.assertEquals(15, control); control = 0; get("/").produces("FILTERED"); Assert.assertEquals(15, control); }</code><technical_language>Get rid of System.out.println, feedback provided assertions</technical_language>

Target:
public void multi_filter() { List<String> filters = new ArrayList<>(); server.configure(routes -> routes. get("/", "NOT FILTERED"). get("/other", "OTHER"). filter((uri, context, nextFilter) -> { filters.add("filter 1"); return nextFilter.get(); }) .filter((uri, context, nextFilter) -> { filters.add("filter 2"); if ("/".equals(uri)) { return new Payload("text/html", "FILTERED"); } return nextFilter.get(); })); get("/other").produces("OTHER"); assertThat(filters).containsExactly("filter 1", "filter 2"); filters.clear(); get("/").produces("FILTERED"); assertThat(filters).containsExactly("filter 1", "filter 2"); }
Source:
<code>public ServicePort expose( KubernetesEnvironment k8sEnv, String backendServiceName, int backendServicePort, String protocol) throws InfrastructureException { ensureJwtProxyInjected(k8sEnv); int listenPort = availablePort++; proxyConfigBuilder.addVerifierProxy( listenPort, "http://" + backendServiceName + ":" + backendServicePort); k8sEnv .getConfigMaps() .get(getConfigMapName()) .getData() .put(JWT_PROXY_CONFIG_FILE, proxyConfigBuilder.build()); ServicePort exposedPort = new ServicePortBuilder() .withName(backendServiceName + "-" + listenPort) .withPort(listenPort) .withProtocol(protocol) .withNewTargetPort(listenPort) .build(); k8sEnv.getServices().get(getServiceName()).getSpec().getPorts().add(exposedPort); <START> return exposedPort; <END> }</code><technical_language>get some use-cases. willing explain me? 1. if 2 workspace masters running time? 1. if workspaces get deployed single k8s namespace? 1. Is guarantee this class created multiple times is a singleton is created automatically DI container</technical_language>

Target:
public ServicePort expose( KubernetesEnvironment k8sEnv, String backendServiceName, int backendServicePort, String protocol) throws InfrastructureException { ensureJwtProxyInjected(k8sEnv); int listenPort = availablePort++; proxyConfigBuilder.addVerifierProxy( listenPort, "http://" + backendServiceName + ":" + backendServicePort); k8sEnv .getConfigMaps() .get(getConfigMapName()) .getData() .put(JWT_PROXY_CONFIG_FILE, proxyConfigBuilder.build()); ServicePort exposedPort = new ServicePortBuilder() .withName("server-" + listenPort) .withPort(listenPort) .withProtocol(protocol) .withNewTargetPort(listenPort) .build(); k8sEnv.getServices().get(getServiceName()).getSpec().getPorts().add(exposedPort); return exposedPort; }
Source:
<code>public void startServerLazily(SensorContext context) throws IOException { if (failedToStart) { <START> throw new NodeCommandException("Failed to start SonarJS eslint-bridge before, will not attempt again."); <END> } try { if (isAlive()) { LOG.debug("SonarJS eslint-bridge server is up, no need to start."); return; } deploy(); startServer(context); } catch (NodeCommandException e) { LOG.error(e.getMessage(), e); failedToStart = true; throw e; } }</code><technical_language>rephrasing? e.g. Skipping start of eslint-bridge server due failure analysis</technical_language>

Target:
public void startServerLazily(SensorContext context) throws IOException, ServerAlreadyFailedException, NodeCommandException { if (failedToStart) { throw new ServerAlreadyFailedException(); } try { if (isAlive()) { LOG.debug("SonarJS eslint-bridge server is up, no need to start."); return; } deploy(); startServer(context); } catch (NodeCommandException e) { failedToStart = true; throw e; } }
Source:
<code>public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); uiController.setupUI(); <START> appUpdateController = AppUpdateControllerFactory.create(this::handleAppUpdate, getApplicationContext()); <END> appUpdateController.register(); }</code><technical_language>move in app update code HomeScreenBaseActivity in order support versions of home activity</technical_language>

Target:
public void onCreateSessionSafe(Bundle savedInstanceState) { super.onCreateSessionSafe(savedInstanceState); uiController.setupUI(); }
Source:
<code><START> protected Class<? extends BaseBlockRender> getRenderer() <END> { return RenderQNB.class; }</code><technical_language>raw</technical_language>

Target:
protected Class<? extends RenderQNB> getRenderer() { return RenderQNB.class; }
Source:
<code><START> private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { <END> boolean needMore = false; while (true) { if (needMore) { readMore(buffer, input, bytesRemaining); needMore = false; } if (buffer.remaining() < 1 && bytesRemaining.value > 0) { needMore = true; } else { return buffer.get(); } } }</code><technical_language>I simplify functions. this: java private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1) readMore(buffer, input, bytesRemaining); return buffer.get(); } private static long readVarLong(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarlong(buffer); } private static int readVarInt(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 10 && bytesRemaining.value > 0) readMore(buffer, input, bytesRemaining); return ByteUtils.readVarint(buffer); } I need more call readMore</technical_language>

Target:
private static byte readByte(ByteBuffer buffer, DataInput input, IntRef bytesRemaining) throws IOException { if (buffer.remaining() < 1 && bytesRemaining.value > 0) { readMore(buffer, input, bytesRemaining); } return buffer.get(); }
Source:
<code>protected AbstractConfig getConfig() { if(config == null) { <START> throw new IllegalStateException("The configuration has not been set yet. Invoke start(props) first."); <END> } return config; }</code><technical_language>doc'd function parameters type, name: start(Map)</technical_language>

Target:
protected AbstractConfig getConfig() { if(config == null) { throw new IllegalStateException("The configuration has not been set yet. Invoke start(Map) first."); } return config; }
Source:
<code>public String getLabel() { <START> return "Drop Association as ReadLinkAction"; <END> }</code><technical_language>Missing NLS</technical_language>

Target:
public String getLabel() { return Messages.AssociationToReadLinkActionDropStrategy_Label; }
Source:
<code>private boolean isWithSecurityEnforced(final AbstractApexNode<?> node){ if(node instanceof ASTSoqlExpression){ <START> String pattern = "(?i).*[^']\\s*WITH SECURITY_ENFORCED\\s*[^']*"; String query = ((ASTSoqlExpression) node).getQuery(); return query.matches(pattern); <END> } return false; }</code><technical_language>node.getNode().getQuery().endsWith("WITH SECURITY_ENFORCED"); produce result</technical_language>

Target:
private boolean isWithSecurityEnforced(final AbstractApexNode<?> node) { if (node instanceof ASTSoqlExpression) { boolean temp = WITH_SECURITY_ENFORCED.matcher(((ASTSoqlExpression) node).getQuery()).matches(); return temp; } return false; }
Source:
<code>public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments, String externalExecutionId) { TaskExecution taskExecution = new TaskExecution(executionId, null, taskName, startTime, null, null, arguments, null, externalExecutionId); <START> Object[] queryParameters = new Object[]{ startTime, taskName, <END> new Date(), externalExecutionId, executionId}; int[] argTypes = new int[]{ Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP, Types.VARCHAR, Types.BIGINT }; String updateString = START_TASK_EXECUTION_PREFIX + START_TASK_EXECUTION_EXTERNAL_ID_SUFFIX; if(externalExecutionId == null) { queryParameters = new Object[]{startTime, taskName, new Date(), executionId}; updateString = START_TASK_EXECUTION_PREFIX + START_TASK_EXECUTION_SUFFIX; argTypes = new int[]{Types.TIMESTAMP, Types.VARCHAR, Types.TIMESTAMP, Types.BIGINT}; } jdbcTemplate.update(getQuery(updateString), queryParameters, argTypes); insertTaskArguments(executionId, arguments); return taskExecution; }</code><technical_language>small pick here. For efficiency, create this array in else of if statement (instead of creating arrays. for argTypes arrays well</technical_language>

Target:
public TaskExecution startTaskExecution(long executionId, String taskName, Date startTime, List<String> arguments, String externalExecutionId) { return startTaskExecution(executionId, taskName, startTime, arguments, externalExecutionId, null); }
Source:
<code>public void failuresSavedIfFetchKeysThrows() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); <START> Set<Integer> failures = mock(Set.class); <END> InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); doThrow(new ForceReattemptException("")).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(failures).add(1); verify(spyPartitionedRegion, never()).getValuesForKeys(values, serverConnection, null); }</code><technical_language>mock Collections. fine actual Set here</technical_language>

Target:
public void failuresSavedIfFetchKeysThrows() throws Exception { PartitionedRegion spyPartitionedRegion = spy(partitionedRegion); VersionedObjectList values = mock(VersionedObjectList.class); ServerConnection serverConnection = mock(ServerConnection.class); Set<Integer> failures = new HashSet<>(); InternalDistributedMember member = mock(InternalDistributedMember.class); Set<Integer> buckets = new HashSet<>(); buckets.add(1); doThrow(new ForceReattemptException("")).when(spyPartitionedRegion).getFetchKeysResponse(member, 1); spyPartitionedRegion.fetchKeysAndValues(values, serverConnection, failures, member, null, buckets); verify(spyPartitionedRegion, never()).getValuesForKeys(values, serverConnection, null); assertThat(failures.contains(1)).isTrue(); }
Source:
<code>private void initializeDefaultProjectAfterDelete() { getActivity().findViewById(R.id.fragment_container).setVisibility(View.GONE); <START> getActivity().findViewById(R.id.progress_circle).setVisibility(View.VISIBLE); <END> asyncTask = new AsyncTask<Void, Void, Activity>() { @Override protected Activity doInBackground(Void... params) { ProjectManager.getInstance().initializeDefaultProject(getActivity()); return getActivity(); } @Override protected void onPostExecute(Activity activity) { activity.findViewById(R.id.fragment_container).setVisibility(View.VISIBLE); activity.findViewById(R.id.progress_circle).setVisibility(View.GONE); initializeList(); } }.execute(); }</code><technical_language>IMO code is easier understand onPreExecute() for this code. * pre (Show loading spinner) * run (init default project update list) * post (Hide loading spinner) do think</technical_language>

Target:
private void initializeDefaultProjectAfterDelete() { final Activity activity = getActivity(); projectInitializer = new AsyncTask<Void, Void, Void>() { @Override protected void onPreExecute() { activity.findViewById(R.id.fragment_container).setVisibility(View.GONE); activity.findViewById(R.id.progress_circle).setVisibility(View.VISIBLE); } @Override protected Void doInBackground(Void... params) { ProjectManager.getInstance().initializeDefaultProject(activity); return null; } @Override protected void onPostExecute(Void aVoid) { activity.findViewById(R.id.fragment_container).setVisibility(View.VISIBLE); activity.findViewById(R.id.progress_circle).setVisibility(View.GONE); initializeList(); } }.execute(); }
Source:
<code>public boolean tableExists( Connection connection, TableId tableId ) throws SQLException { <START> log.info("Checking dialect for existance of table {}", this, tableId); <END> try (ResultSet rs = connection.getMetaData().getTables( tableId.catalogName(), tableId.schemaName(), tableId.tableName(), new String[]{"TABLE"} )) { final boolean exists = rs.next(); log.info("Using dialect table {}", this, tableId, exists ? "present" : "absent"); return exists; } }</code><technical_language>Nit: existence instead of existance</technical_language>

Target:
public boolean tableExists( Connection connection, TableId tableId ) throws SQLException { log.info("Checking dialect for existence of table {}", this, tableId); try (ResultSet rs = connection.getMetaData().getTables( tableId.catalogName(), tableId.schemaName(), tableId.tableName(), new String[]{"TABLE"} )) { final boolean exists = rs.next(); log.info("Using dialect table {}", this, tableId, exists ? "present" : "absent"); return exists; } }
Source:
<code>public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { <START> return HTMLPageAssetRenderedBuilder.get() <END> .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }</code><technical_language>this is right do builder, a separated class new HTMLPageAssetRenderedBuilder().htmlPageAsset(page).user(user).request(request).....build()</technical_language>

Target:
public HTMLPageAssetRendered getPageRendered(final HttpServletRequest request, final HttpServletResponse response, final User user, final HTMLPageAsset page, PageMode pageMode) throws DotDataException, DotSecurityException, IOException { return new HTMLPageAssetRenderedBuilder() .setHtmlPageAsset(page) .setUser(user) .setRequest(request) .setResponse(response) .setSite(resolveSite(request, user)) .build(); }
Source:
<code>public long getSerial() { <START> long next = getAttribute(SERIAL) + 1; <END> setAttribute(SERIAL, next); return next; }</code><technical_language>synchronize this Object mutex</technical_language>

Target:
public long getSerial() { synchronized (serialMutex) { long next = getAttribute(SERIAL) + 1; setAttribute(SERIAL, next); return next; } }
Source:
<code>public void commit() { switch (state()) { case RUNNING: stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); <START> changelogOffsetSnapshot = stateMgr.changelogOffsets(); <END> log.info("Committed"); break; case CLOSING: log.trace("Skip committing since task is closing"); break; default: throw new IllegalStateException("Illegal state " + state() + " while committing standby task " + id); } }</code><technical_language>a copy of map, guard state manager implementation</technical_language>

Target:
public void commit() { switch (state()) { case RUNNING: stateMgr.flush(); stateMgr.checkpoint(Collections.emptyMap()); offsetSnapshotSinceLastCommit = new HashMap<>(stateMgr.changelogOffsets()); log.info("Committed"); break; case CLOSING: log.trace("Skip committing since task is closing"); break; default: throw new IllegalStateException("Illegal state " + state() + " while committing standby task " + id); } }
Source:
<code>public static Optional<UsState> getState(String normalisedZipCode) { if (WELL_FORMED_STATE_WITH_ZIP_CODE.matcher(normalisedZipCode).matches() || WELL_FORMED_STATE_WITH_ZIP_FOUR_PLUS.matcher(normalisedZipCode).matches()) { return getStateFromZipCodeAndState(normalisedZipCode); } else if (WELL_FORMED_ZIP_CODE.matcher(normalisedZipCode).matches() || WELL_FORMED_ZIP_FOUR_PLUS.matcher(normalisedZipCode).matches()) { <START> return getStateFromZipCode(normalisedZipCode.substring(0, 3)); <END> } return Optional.empty(); }</code><technical_language>trick regex extract characters</technical_language>

Target:
public static Optional<UsState> getState(String normalisedZipCode) { var wellFormedZipCodeAndOptionalPlusFourMatcher = WELL_FORMED_STATE_WITH_ZIP_CODE_AND_OPTIONAL_PLUS_FOUR.matcher(normalisedZipCode); var wellFormedStateWithZipAndOptionalPlusFourMatcher = WELL_FORMED_ZIP_CODE_AND_OPTIONAL_PLUS_FOUR.matcher(normalisedZipCode); if (wellFormedStateWithZipAndOptionalPlusFourMatcher.matches()) { String stateAbbreviation = wellFormedStateWithZipAndOptionalPlusFourMatcher.group(1); return Optional.ofNullable(UsZipCodeToStateMap.ZIP_CODE_TO_US_STATE_ABBREVIATIONS.get(stateAbbreviation)); } else if (wellFormedZipCodeAndOptionalPlusFourMatcher.matches()) { String firstThreeCharacters = wellFormedZipCodeAndOptionalPlusFourMatcher.group(1); return Optional.ofNullable(US_STATE_ABBREVIATIONS_MAPPING.get(firstThreeCharacters)); } return Optional.empty(); }