auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getTemplateType() != VmEntityType.INSTANCE_TYPE) { <START> validate(getVirtioRngValidator().canAddRngDevice(getVdsGroup(), getParameters().getRngDevice())); <END> } if (getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_NOT_FOUND); } return true; }</code><technical_language>here, missing return statement</technical_language>

Target:
protected boolean canDoAction() { if (!super.canDoAction()) { return false; } if (getTemplateType() != VmEntityType.INSTANCE_TYPE) { if (!validate(getVirtioRngValidator().canAddRngDevice(getVdsGroup(), getParameters().getRngDevice()))) { return false; } } if (getRngDevices().isEmpty()) { return failCanDoAction(VdcBllMessages.ACTION_TYPE_FAILED_RNG_NOT_FOUND); } return true; }
Source:
<code>public void onGetEndUserIdSuccess(long endUserId) { endUser.setId(endUserId); if(this.endUser.hasProperties() || this.endUser.getExternalId() != null || this.endUser.getPhoneNumber() != null) { sendUpdateEndUserRequest(); <START> } <END> showSurvey(); }</code><technical_language>do of this instead? java if(this.endUser.hasProperties() || this.endUser.getExternalId() || this.endUser.getPhoneNumber()) { sendUpdateEndUserRequest(); } validation in presence enough</technical_language>

Target:
public void onGetEndUserIdSuccess(long endUserId) { endUser.setId(endUserId); if(this.endUser.hasProperties() || this.endUser.hasExternalId() || this.endUser.hasPhoneNumber()) { sendUpdateEndUserRequest(); } showSurvey(); }
Source:
<code>private static void putDocumentWithRetry(String indexName, final Document document) throws TeammatesException, MaximumRetriesExceededException { final Index index = getIndex(indexName); <START> RM.runUntilSuccessful(new RetryableTaskReturnsThrows<OperationResult, TeammatesException>("Put document") { <END> @Override public OperationResult run() { try { PutResponse response = index.put(document); return response.getResults().get(0); } catch (PutException e) { return e.getOperationResult(); } } public boolean isSuccessful(OperationResult result) throws TeammatesException { finalMessage = result.getMessage(); if (StatusCode.OK.equals(result.getCode())) { return true; } else if (StatusCode.TRANSIENT_ERROR.equals(result.getCode())) { return false; } else { throw new TeammatesException(finalMessage); } } }); }</code><technical_language>if TeammatesException denote some sort of logical error in system, failure datastore GAE</technical_language>

Target:
private static void putDocumentWithRetry(String indexName, final Document document) throws PutException, MaximumRetriesExceededException { final Index index = getIndex(indexName); RM.runUntilSuccessful(new RetryableTaskThrows<PutException>("Put document") { private OperationResult lastResult; @Override public void run() { try { PutResponse response = index.put(document); lastResult = response.getResults().get(0); } catch (PutException e) { lastResult = e.getOperationResult(); } } @Override public boolean isSuccessful() throws PutException { finalMessage = lastResult.getMessage(); if (StatusCode.OK.equals(lastResult.getCode())) { return true; } else if (StatusCode.TRANSIENT_ERROR.equals(lastResult.getCode())) { return false; } else { throw new PutException(lastResult); } } }); }
Source:
<code>protected List<String> getPropertiesToHide(ScenarioGridColumn selectedColumn, ScenarioGridModel scenarioGridModel) { List<String> toReturn = new ArrayList<>(); <START> if (selectedColumn != null && !selectedColumn.isPropertyAssigned()) { <END> scenarioGridModel.getSimulation().ifPresent(simulation -> { final SimulationDescriptor simulationDescriptor = simulation.getSimulationDescriptor(); List<ScenarioGridColumn> instanceColumns = scenarioGridModel.getInstanceScenarioGridColumns(selectedColumn); toReturn.addAll(instanceColumns.stream() .filter(ScenarioGridColumn::isPropertyAssigned) .map(instanceColumn -> scenarioGridModel.getColumns().indexOf(instanceColumn)) .map(columnIndex -> { String propertyString = String.join(".", simulationDescriptor.getFactMappingByIndex(columnIndex).getExpressionElementsWithoutClass() .stream() .map(ExpressionElement::getStep) .collect(Collectors.toList())); propertyString = propertyString.isEmpty() ? "value" : propertyString; return propertyString; }) .collect(Collectors.toList())); }); } return toReturn; }</code><technical_language>@yesamer I issues 1) getPropertiesToHide is meant need selected column, throw exception if selectedColumn is null (because means is a bug in calling code) - if find a enforce please do 2) if undo/redo needs call method, means some needed information missing status, add there; differently, calling undo/redo, status informations needs set scenario</technical_language>

Target:
protected List<String> getPropertiesToHide(ScenarioGridColumn selectedColumn, ScenarioGridModel scenarioGridModel) { List<String> toReturn = new ArrayList<>(); if (!selectedColumn.isPropertyAssigned()) { scenarioGridModel.getSimulation().ifPresent(simulation -> { final SimulationDescriptor simulationDescriptor = simulation.getSimulationDescriptor(); List<ScenarioGridColumn> instanceColumns = scenarioGridModel.getInstanceScenarioGridColumns(selectedColumn); toReturn.addAll(instanceColumns.stream() .filter(ScenarioGridColumn::isPropertyAssigned) .map(instanceColumn -> scenarioGridModel.getColumns().indexOf(instanceColumn)) .map(columnIndex -> { String propertyString = String.join(".", simulationDescriptor.getFactMappingByIndex(columnIndex).getExpressionElementsWithoutClass() .stream() .map(ExpressionElement::getStep) .collect(Collectors.toList())); propertyString = propertyString.isEmpty() ? "value" : propertyString; return propertyString; }) .collect(Collectors.toList())); }); } return toReturn; }
Source:
<code>public static void enrichDiskByJsonDescription(String jsonDiskDescription, Disk disk) throws IOException { Map<String, Object> diskDescriptionMap = JsonHelper.jsonToMap(jsonDiskDescription); disk.setDiskAlias((String) diskDescriptionMap.get(DISK_ALIAS)); <START> disk.setDiskDescription((String) diskDescriptionMap.get(DISK_DESCRIPTION)); <END> }</code><technical_language>This assumes json helper parses values strings. play safe toString() instead of a cast</technical_language>

Target:
public static void enrichDiskByJsonDescription(String jsonDiskDescription, Disk disk) throws IOException { Map<String, Object> diskDescriptionMap = JsonHelper.jsonToMap(jsonDiskDescription); disk.setDiskAlias(diskDescriptionMap.get(DISK_ALIAS).toString()); disk.setDiskDescription(diskDescriptionMap.get(DISK_DESCRIPTION).toString()); }
Source:
<code>public TwigAssetCompletionContributor() { extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetPattern(), new AssetCompletionProvider().setAssetParser( new AssetDirectoryReader() )); extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetTag("stylesheets"), new AssetCompletionProvider().setAssetParser( <START> new AssetDirectoryReader().setFilterExtension("css").setIncludeBundleDir(true) <END> )); extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetTag("javascripts"), new AssetCompletionProvider().setAssetParser( new AssetDirectoryReader().setFilterExtension("js").setIncludeBundleDir(true) )); }</code><technical_language>support .less some other formats</technical_language>

Target:
public TwigAssetCompletionContributor() { extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetPattern(), new AssetCompletionProvider().setAssetParser( new AssetDirectoryReader() )); extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetTag("stylesheets"), new AssetCompletionProvider().setAssetParser( new AssetDirectoryReader().setFilterExtension("css", "less", "sass").setIncludeBundleDir(true) )); extend(CompletionType.BASIC, TwigHelper.getAutocompletableAssetTag("javascripts"), new AssetCompletionProvider().setAssetParser( new AssetDirectoryReader().setFilterExtension("js", "dart", "coffee").setIncludeBundleDir(true) )); }
Source:
<code>public void testTimestampRangeFilterWithMaxVal() throws IOException { int numCols = Integer.MAX_VALUE; Long start = (long) (Integer.MAX_VALUE - 2); String goodValue = "includeThisValue"; Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("testRow-TimestampRange-"); Put put = new Put(rowKey); <START> for (Long i = start; i < numCols; ++i) { <END> put.addColumn(COLUMN_FAMILY, dataHelper.randomData(""), i, Bytes.toBytes(goodValue)); } table.put(put); FilterList filter = new FilterList(FilterList.Operator.MUST_PASS_ALL, new TimestampRangeFilter(start, Integer.MAX_VALUE), new FamilyFilter(CompareOp.EQUAL, new BinaryComparator(Bytes.toBytes("test_family")))); Get get = new Get(rowKey).setFilter(filter); Result result = table.get(get); Cell[] cells = result.rawCells(); Assert.assertEquals("Should have all cells.", 2, cells.length); long[] timestamps = new long[] { cells[0].getTimestamp(), cells[1].getTimestamp() }; Arrays.sort(timestamps); Assert.assertArrayEquals(new long[] { start, Integer.MAX_VALUE-1 }, timestamps); table.close(); }</code><technical_language>Long i long i. Please inline start numCols here</technical_language>

Target:
public void testTimestampRangeFilterWithMaxVal() throws IOException { long numCols = Integer.MAX_VALUE; long start = Integer.MAX_VALUE - 2; String goodValue = "includeThisValue"; Table table = getDefaultTable(); byte[] rowKey = dataHelper.randomData("testRow-TimestampRange-"); Put put = new Put(rowKey); for (long i = start; i < numCols; ++i) { put.addColumn(COLUMN_FAMILY, dataHelper.randomData(""), i, Bytes.toBytes(goodValue)); } table.put(put); Filter filter = new TimestampRangeFilter(start, Integer.MAX_VALUE); Get get = new Get(rowKey).setFilter(filter); Result result = table.get(get); Cell[] cells = result.rawCells(); Assert.assertEquals("Should have all cells.", 2, cells.length); long[] timestamps = new long[] { cells[0].getTimestamp(), cells[1].getTimestamp() }; Arrays.sort(timestamps); Assert.assertArrayEquals(new long[] { start, Integer.MAX_VALUE-1 }, timestamps); table.close(); }
Source:
<code>public String getSelectedSite(final List<Host> siteList, final String siteInSession, User user) { String selectedSite = UtilMethods.isSet(siteInSession) ? siteInSession : StringUtils.EMPTY; boolean siteFound = false; if (siteList != null && !siteList.isEmpty()) { Host host = null; try { host = this.hostAPI.find(siteInSession, user, Boolean.FALSE); } catch (DotDataException e) { } catch (DotSecurityException e) { } if (null != host && UtilMethods.isSet(host.getIdentifier())) { siteFound = true; <START> if(!siteList.contains(host)){ <END> siteList.add(host); } } if (!siteFound) { selectedSite = siteList.get(0).getIdentifier(); } } return selectedSite; }</code><technical_language>i do context, a more efficient structure here, Set. contains Log (N) instead of O (N)</technical_language>

Target:
public String getSelectedSite(final List<Host> siteList, final String siteInSession, User user) { String selectedSite = UtilMethods.isSet(siteInSession) ? siteInSession : StringUtils.EMPTY; boolean siteFound = false; if (siteList != null && !siteList.isEmpty()) { Host host = null; try { host = this.hostAPI.find(siteInSession, user, Boolean.FALSE); } catch (DotDataException | DotSecurityException e) { debug(SiteHelper.class, "User doesn't have permission to see host ["+siteInSession+"}. error"+e.getMessage()); } if (null != host && UtilMethods.isSet(host.getIdentifier())) { siteFound = true; if(!siteList.contains(host)){ siteList.add(host); } } if (!siteFound) { selectedSite = siteList.get(0).getIdentifier(); } } return selectedSite; }
Source:
<code>public JsonNode set(String name, JsonNode jsonNode) { <START> return JsonNodeUtils.fromJacksonNode(objectNode.replace(name, JsonNodeUtils.toJacksonNode(jsonNode))); <END> }</code><technical_language>NPE, [replace](<LINK_0>,%20com.fasterxml.jackson.databind.JsonNode)) return null</technical_language>

Target:
public JsonNode set(String name, JsonNode jsonNode) { com.fasterxml.jackson.databind.JsonNode oldValue = objectNode.replace(name, JsonNodeUtils.toJacksonNode(jsonNode)); return (oldValue == null) ? null : JsonNodeUtils.fromJacksonNode(oldValue); }
Source:
<code>public static Booleans copyOrUpdate(Realm realm, Booleans object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( <START> "Objects belonging to Realm instances in other threads cannot be copied into this Realm instance."); <END> } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } return copy(realm, object, update, cache); }</code><technical_language>"belonging" -> "which belong"</technical_language>

Target:
public static Booleans copyOrUpdate(Realm realm, Booleans object, boolean update, Map<RealmObject,RealmObjectProxy> cache) { if (((RealmObject) object).realm != null && ((RealmObject) object).realm.threadId != realm.threadId) { throw new IllegalArgumentException( "Objects which belong to Realm instances in other threads cannot be copied into this Realm instance."); } if (((RealmObject) object).realm != null && ((RealmObject) object).realm.getPath().equals(realm.getPath())) { return object; } return copy(realm, object, update, cache); }
Source:
<code>public SnomedRefSetSearchRequestBuilder filterByMapTargetComponentType(String mapTargetComponentType) { <START> if (Strings.isNullOrEmpty(mapTargetComponentType)) { <END> return getSelf(); } if (TerminologyRegistry.UNSPECIFIED.equals(mapTargetComponentType)) { return getSelf(); } final int referencedComponentTypeAsInt = TerminologyRegistry.INSTANCE.getTerminologyComponentById(mapTargetComponentType).shortId(); return filterByMapTargetComponentType(referencedComponentTypeAsInt); }</code><technical_language>put conditional blocks filterBy methods. Handle in actual Request implementation instead. if needed. This filter reference sets mapTargetComponentType is UNSPECIFIED. Null values values do generate actual clauses in search requests. Please refactor</technical_language>

Target:
public SnomedRefSetSearchRequestBuilder filterByMapTargetComponentType(String mapTargetComponentType) { if (Strings.isNullOrEmpty(mapTargetComponentType)) { return getSelf(); } final int referencedComponentTypeAsInt = TerminologyRegistry.INSTANCE.getTerminologyComponentById(mapTargetComponentType).shortId(); return filterByMapTargetComponentType(referencedComponentTypeAsInt); }
Source:
<code>void registerCommandOnce() { if (this.commandRegistered.compareAndSet(false, true)) { Sponge.getGame().getCommandDispatcher().register(Sponge.getPlugin(), CommandSpec.builder() .description(t("Helper command for paginations occurring")) <START> .arguments(new ActivePaginationCommandElement(t("pagination-id")), integer(t("page"))) <END> .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().sendPage(args.<Integer>getOne("page").get()); return CommandResult.success(); } }).build(), "pagination", "page"); } }</code><technical_language>This reduces usability for console other environments clickable text is available</technical_language>

Target:
void registerCommandOnce() { if (this.commandRegistered.compareAndSet(false, true)) { Sponge.getGame().getCommandDispatcher().register(Sponge.getPlugin(), CommandSpec.builder() .description(t("Helper command for paginations occurring")) .arguments(new ActivePaginationCommandElement(t("pagination-id"))) .child(CommandSpec.builder() .description(t("Go to the next page")) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().nextPage(); return CommandResult.success(); } }).build(), "next", "n") .child(CommandSpec.builder() .description(t("Go to the previous page")) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().previousPage(); return CommandResult.success(); } }).build(), "previous", "prev", "p") .child(CommandSpec.builder() .description(t("Go to a specific page")) .arguments(integer(t("page"))) .executor(new CommandExecutor() { @Override public CommandResult execute(CommandSource src, CommandContext args) throws CommandException { args.<ActivePagination>getOne("pagination-id").get().specificPage(args.<Integer>getOne("page").get()); return CommandResult.success(); } }).build(), "page") .build(), "pagination", "page"); } }
Source:
<code>public void testConfigurePipelineSchemaValidation() throws Exception { <START> MockTestConfigurer mockConfigurer = new MockTestConfigurer(Schema.of(Schema.Type.BYTES)); <END> S3_TRANSFORM.configurePipeline(mockConfigurer); Assert.assertEquals(LOG_SCHEMA, mockConfigurer.getOutputSchema()); mockConfigurer = new MockTestConfigurer(Schema.of(Schema.Type.STRING)); S3_TRANSFORM.configurePipeline(mockConfigurer); Assert.assertEquals(LOG_SCHEMA, mockConfigurer.getOutputSchema()); }</code><technical_language>expect schemas of type RECORD. This is a good test case though, check this throws exception</technical_language>

Target:
public void testConfigurePipelineSchemaValidation() throws Exception { Schema inputSchemaString = Schema.recordOf( "event", Schema.Field.of("CLF", Schema.of(Schema.Type.STRING)), Schema.Field.of("body", Schema.of(Schema.Type.STRING))); MockPipelineConfigurer mockConfigurer = new MockPipelineConfigurer(inputSchemaString); S3_TRANSFORM.configurePipeline(mockConfigurer); Assert.assertEquals(LOG_SCHEMA, mockConfigurer.getOutputSchema()); Schema inputSchemaBytes = Schema.recordOf( "event", Schema.Field.of("CLF", Schema.of(Schema.Type.STRING)), Schema.Field.of("body", Schema.of(Schema.Type.BYTES))); mockConfigurer = new MockPipelineConfigurer(inputSchemaBytes); CLF_TRANSFORM.configurePipeline(mockConfigurer); Assert.assertEquals(LOG_SCHEMA, mockConfigurer.getOutputSchema()); }
Source:
<code>private AlarmType getAlarmType(final Map<String, String> parameters, final int index) { final String key = PlatformSmartmeteringKeys.ALARM_TYPE + "_" + index; <START> if (parameters.containsKey(key)) { <END> return AlarmType.fromValue(parameters.get(key)); } return DEFAULT_ALARM_TYPE; }</code><technical_language>Consider methods a default parameter Helpers avoid repeating if-contains-key-else-return-default code</technical_language>

Target:
private AlarmType getAlarmType(final Map<String, String> parameters, final int index) { final String key = SettingsHelper.makeKey(PlatformSmartmeteringKeys.ALARM_TYPE, index); return Helpers.getEnum(parameters, key, AlarmType.class, DEFAULT_ALARM_TYPE); }
Source:
<code>private AmplifyStateTracker( @NonNull final Context context, @NonNull final ILogger logger) { this.applicationContext = context.getApplicationContext(); this.logger = logger; <START> this.lastEventTimePredicates = new LastTimeMap(logger, applicationContext); <END> this.firstEventTimePredicates = new FirstTimeMap(logger, applicationContext); this.lastEventVersionPredicates = new LastVersionMap(logger, applicationContext); this.totalEventCountPredicates = new TotalCountMap(logger, applicationContext); }</code><technical_language>moved if injecting</technical_language>

Target:
private AmplifyStateTracker( @NonNull final Context context, @NonNull final ILogger logger) { this.applicationContext = context.getApplicationContext(); this.logger = logger; this.lastTimePredicate = new LastTimePredicate(logger, applicationContext); this.firstTimePredicate = new FirstTimePredicate(logger, applicationContext); this.lastVersionPredicate = new LastVersionPredicate(logger, applicationContext); this.totalCountPredicate = new TotalCountPredicate(logger, applicationContext); }
Source:
<code><K, V> void pipeRecord(final String topic, final TestRecord<K, V> record, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final Instant time) { final byte[] serializedKey = keySerializer.serialize(topic, record.headers(), record.key()); final byte[] serializedValue = valueSerializer.serialize(topic, record.headers(), record.value()); long timestamp = 0; <START> if (time != null) <END> timestamp = time.toEpochMilli(); else if (record.timestamp() != null) timestamp = record.timestamp(); pipeRecord(topic, timestamp, serializedKey, serializedValue, record.headers()); }</code><technical_language>nit: add braces (preferred for blocks)</technical_language>

Target:
<K, V> void pipeRecord(final String topic, final TestRecord<K, V> record, final Serializer<K> keySerializer, final Serializer<V> valueSerializer, final Instant time) { final byte[] serializedKey = keySerializer.serialize(topic, record.headers(), record.key()); final byte[] serializedValue = valueSerializer.serialize(topic, record.headers(), record.value()); long timestamp = 0; if (time != null) { timestamp = time.toEpochMilli(); } else if (record.timestamp() != null) { timestamp = record.timestamp(); } pipeRecord(topic, timestamp, serializedKey, serializedValue, record.headers()); }
Source:
<code>public StatusOnlyReturnForXmlRpc glusterVolumeStart(String volumeName, Boolean force) { try { <START> return new StatusOnlyReturnForXmlRpc(vdsServer.glusterVolumeStart(volumeName, force.toString())); <END> } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }</code><technical_language>I "force" variable passed vdsServer method is, instead of converting string</technical_language>

Target:
public StatusOnlyReturnForXmlRpc glusterVolumeStart(String volumeName, Boolean force) { try { return new StatusOnlyReturnForXmlRpc(vdsServer.glusterVolumeStart(volumeName, force)); } catch (UndeclaredThrowableException ute) { throw new XmlRpcRunTimeException(ute); } }
Source:
<code><START> public @ResponseBody List<Member> getPlayersForTeam( <END> HttpSession session, @PathVariable int id) { if (session.getAttribute("member") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); return (List<Member>) team.getPlayers(); }</code><technical_language>this return type changed avoid list cast</technical_language>

Target:
public @ResponseBody Set<Member> getPlayersForTeam( HttpSession session, @PathVariable int id) { if (session.getAttribute("member") == null) { return null; } TeamDao teamDao = new TeamDao(); Team team = teamDao.getTeamById(id, false, true, false); return team.getPlayers(); }
Source:
<code>public boolean onTouchEvent(MotionEvent ev) { lastActiveGestureDetector = realObject; onTouchEventMotionEvent = ev; <START> return directlyOn(realObject, GestureDetector.class, "onTouchEvent", from(MotionEvent.class, ev)); <END> }</code><technical_language>directlyOn() version returns object instead, slightly performance type safe</technical_language>

Target:
public boolean onTouchEvent(MotionEvent ev) { lastActiveGestureDetector = realObject; onTouchEventMotionEvent = ev; return directlyOn(realObject, GestureDetector.class).onTouchEvent(ev); }
Source:
<code>private void initRenderingModules() { renderingModuleRegistry = context.get(RenderingModuleRegistry.class); if (renderingModuleRegistry.getOrderedRenderingModules().isEmpty()) { <START> renderingModuleRegistry.updateRenderingModulesOrder(context.get(ModuleManager.class).getEnvironment(), context); <END> if(renderingModuleRegistry.getOrderedRenderingModules().isEmpty()) { GameEngine gameEngine = context.get(GameEngine.class); gameEngine.changeState(new StateMainMenu("No rendering module loaded, unable to render. Try enabling CoreRendering.")); } } else { renderingModuleRegistry.updateModulesContext(context); } for (ModuleRendering moduleRenderingInstance : renderingModuleRegistry.getOrderedRenderingModules()) { if (moduleRenderingInstance.isEnabled()) { logger.info(String.format("\nInitialising rendering class %s from %s module.\n", moduleRenderingInstance.getClass().getSimpleName(), moduleRenderingInstance.getProvidingModule())); moduleRenderingInstance.initialise(); } } requestTaskListRefresh(); }</code><technical_language>there. (via variable)</technical_language>

Target:
private void initRenderingModules() { renderingModuleRegistry = context.get(RenderingModuleRegistry.class); if (renderingModuleRegistry.getOrderedRenderingModules().isEmpty()) { List<ModuleRendering> renderingModules = renderingModuleRegistry.updateRenderingModulesOrder( context.get(ModuleManager.class).getEnvironment(), context); if (renderingModules.isEmpty()) { GameEngine gameEngine = context.get(GameEngine.class); gameEngine.changeState(new StateMainMenu("No rendering module loaded, unable to render. Try enabling CoreRendering.")); } } else { renderingModuleRegistry.updateModulesContext(context); } for (ModuleRendering moduleRenderingInstance : renderingModuleRegistry.getOrderedRenderingModules()) { if (moduleRenderingInstance.isEnabled()) { logger.info(String.format("\nInitialising rendering class %s from %s module.\n", moduleRenderingInstance.getClass().getSimpleName(), moduleRenderingInstance.getProvidingModule())); moduleRenderingInstance.initialise(); } } requestTaskListRefresh(); }
Source:
<code>public void shouldCreatePersonWithFields() { Person fetchedPerson = personAdapter.getPersonByUuid(DEFAULT_CONFIG_NAME, createdPerson.getUuid()); assertEquals(person.getPreferredName().getGivenName(), fetchedPerson.getPreferredName().getGivenName()); assertEquals(person.getPreferredName().getMiddleName(), fetchedPerson.getPreferredName().getMiddleName()); assertEquals(person.getPreferredName().getFamilyName(), fetchedPerson.getPreferredName().getFamilyName()); Person.Address personAddress = person.getPreferredAddress(); Person.Address fetchedPersonAddress = fetchedPerson.getPreferredAddress(); <START> assertEquals(personAddress.getAddress1(), fetchedPersonAddress.getAddress1()); <END> assertEquals(personAddress.getAddress2(), fetchedPersonAddress.getAddress2()); assertEquals(personAddress.getAddress3(), fetchedPersonAddress.getAddress3()); assertEquals(personAddress.getAddress4(), fetchedPersonAddress.getAddress4()); assertEquals(personAddress.getAddress5(), fetchedPersonAddress.getAddress5()); assertEquals(personAddress.getAddress6(), fetchedPersonAddress.getAddress6()); assertEquals(personAddress.getCityVillage(), fetchedPersonAddress.getCityVillage()); assertEquals(personAddress.getStateProvince(), fetchedPersonAddress.getStateProvince()); assertEquals(personAddress.getCountry(), fetchedPersonAddress.getCountry()); assertEquals(personAddress.getCountyDistrict(), fetchedPersonAddress.getCountyDistrict()); assertEquals(personAddress.getPostalCode(), fetchedPersonAddress.getPostalCode()); assertEquals(personAddress.getLatitude(), fetchedPersonAddress.getLatitude()); assertEquals(personAddress.getLongitude(), fetchedPersonAddress.getLongitude()); assertEquals(personAddress.getStartDate(), fetchedPersonAddress.getStartDate()); assertEquals(personAddress.getEndDate(), fetchedPersonAddress.getEndDate()); }</code><technical_language>assert address objects</technical_language>

Target:
public void shouldCreatePersonWithFields() { Person fetchedPerson = personAdapter.getPersonByUuid(DEFAULT_CONFIG_NAME, createdPerson.getUuid()); assertEquals(person.getPreferredName().getGivenName(), fetchedPerson.getPreferredName().getGivenName()); assertEquals(person.getPreferredName().getMiddleName(), fetchedPerson.getPreferredName().getMiddleName()); assertEquals(person.getPreferredName().getFamilyName(), fetchedPerson.getPreferredName().getFamilyName()); assertEquals(person.getPreferredAddress(), fetchedPerson.getPreferredAddress()); }
Source:
<code>public String toString() { return <START> String.join(".", Integer.toString(major), Integer.toString(minor), Integer.toString(micro), <END> qualifier); }</code><technical_language>Eclipse PDE put error marker plug-in is configured JRE 1.7. Changing 1.8 marker away</technical_language>

Target:
public String toString() { return major + DELIMITER + minor + DELIMITER + micro + DELIMITER + qualifier; }
Source:
<code>T remove() { <START> Map.Entry<Long, Queue<T>> workQueue = queuedRequests.get(id); <END> T result = workQueue.getValue().remove(); if (!workQueue.getValue().isEmpty()) { queuedRequests.put(workQueue.getKey(), workQueue.getValue()); } return result; }</code><technical_language>do want getfirst here</technical_language>

Target:
T remove() { Map.Entry<Long, Queue<T>> workQueue = nextTask(); T result = workQueue.getValue().remove(); if (!workQueue.getValue().isEmpty()) { queuedRequests.put(workQueue.getKey(), workQueue.getValue()); } return result; }
Source:
<code>public WriteOptimization getWriteOptimization() { final String writeOptimizationString = this.getOptionValue(WRITE_OPTIMIZATION.getLongOpt()); try { if (writeOptimizationString == null) { return null; } else { return WriteOptimization.valueOf(writeOptimizationString.toUpperCase()); } } catch (final IllegalArgumentException e) { <START> System.err.printf("Error: Unknown write_optimization: %s", writeOptimizationString); <END> System.exit(1); } return null; }</code><technical_language>This follow normal exception handling path caller handle printing of exception</technical_language>

Target:
public WriteOptimization getWriteOptimization() throws BadArgumentException{ final String writeOptimizationString = this.getOptionValue(WRITE_OPTIMIZATION.getLongOpt()); try { if (writeOptimizationString == null) { return null; } else { return WriteOptimization.valueOf(writeOptimizationString.toUpperCase()); } } catch (final IllegalArgumentException e) { throw new BadArgumentException("Error: Unknown write_optimization:" + writeOptimizationString, e); } }
Source:
<code>public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String accessControlAllowHeaders = PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME; String headerValues = getvalues(configuration.getAccessControlAllowHeaders()); if(!headerValues.isEmpty()){ accessControlAllowHeaders = accessControlAllowHeaders + ", " + headerValues; } String clientOrigin = req.getHeader("origin"); resp.setHeader("Access-Control-Allow-Origin", clientOrigin); <START> resp.setHeader("Access-Control-Allow-Methods", getvalues(configuration.getAccessControlAllowMethods())); <END> resp.setHeader("Access-Control-Allow-Headers", accessControlAllowHeaders); resp.setHeader("Access-Control-Expose-Headers", PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME); resp.setHeader("Access-Control-Allow-Credentials", "" + configuration.isAccessControlAllowCredentials()); resp.setHeader("Access-Control-Max-Age", "" + configuration.getAccessControlMaxAge()); chain.doFilter(request, response); }</code><technical_language>this set if configuration contains values. header set</technical_language>

Target:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; HttpServletResponse resp = (HttpServletResponse) response; String accessControlAllowHeaders = PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME; String headerValues = getAsCommaSeparatedList(configuration.getAccessControlAllowHeaders()); if(!headerValues.isEmpty()){ accessControlAllowHeaders = accessControlAllowHeaders + ", " + headerValues; } String allowedMethods = getAsCommaSeparatedList(configuration.getAccessControlAllowMethods()); String clientOrigin = req.getHeader("origin"); resp.setHeader("Access-Control-Allow-Origin", clientOrigin); if(!allowedMethods.isEmpty()){ resp.setHeader("Access-Control-Allow-Methods", allowedMethods); } resp.setHeader("Access-Control-Allow-Headers", accessControlAllowHeaders); resp.setHeader("Access-Control-Expose-Headers", PlatformConstants.CLIENT_ID_HTTP_HEADER_NAME); resp.setHeader("Access-Control-Allow-Credentials", "" + configuration.isAccessControlAllowCredentials()); resp.setHeader("Access-Control-Max-Age", "" + configuration.getAccessControlMaxAge()); chain.doFilter(request, response); }
Source:
<code>public void complete(AeshCompleteOperation co) { LOG.debugf("Completing {0}", co.getBuffer()); cliCompleter.complete(ctx, co, this); if (ctx.getConfig().isColorOutput()) { List<TerminalString> completionCandidates = co.getCompletionCandidates(); List<TerminalString> requiredCandidates = new ArrayList<>(); for (TerminalString candidate : completionCandidates) { if (candidate.toString().endsWith("*") && !"*".equals(candidate.toString())) { TerminalString newCandidate = Util.formatRequired(candidate); requiredCandidates.add(newCandidate); } } <START> completionCandidates.removeIf(candidate -> candidate.toString().endsWith("*")); <END> completionCandidates.addAll(requiredCandidates); } LOG.debugf("Completion candidates {0}", co.getCompletionCandidates()); }</code><technical_language>try avoid usage of lambda, ;-)</technical_language>

Target:
public void complete(AeshCompleteOperation co) { LOG.debugf("Completing {0}", co.getBuffer()); cliCompleter.complete(ctx, co, this); if (ctx.isColorOutput()) { List<TerminalString> completionCandidates = co.getCompletionCandidates(); List<TerminalString> requiredCandidates = new ArrayList<>(); for (TerminalString candidate : completionCandidates) { if (candidate.toString().endsWith("*") && !"*".equals(candidate.toString())) { TerminalString newCandidate = Util.formatRequired(candidate); requiredCandidates.add(newCandidate); } } completionCandidates.removeIf(new Predicate<TerminalString>() { @Override public boolean test(TerminalString candidate) { return candidate.toString().endsWith("*"); } }); completionCandidates.addAll(requiredCandidates); } LOG.debugf("Completion candidates {0}", co.getCompletionCandidates()); }
Source:
<code>protected Query createQuery(ConvertingParameterAccessor accessor) { <START> String queryString = replacePlaceholders(query, accessor, queryIsAlreadyQuoted); <END> Query query = null; if (fieldSpec != null) { String fieldString = replacePlaceholders(fieldSpec, accessor, fieldsAreAlreadyQuoted); query = new BasicQuery(queryString, fieldString); } else { query = new BasicQuery(queryString); } query.with(accessor.getSort()); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Created query %s", query.getQueryObject())); } return query; }</code><technical_language>sense booleans hidden in MongoQueryMethod call method.isCustomQuotedQuery() method.isCustomQuotedFields</technical_language>

Target:
protected Query createQuery(ConvertingParameterAccessor accessor) { String queryString = replacePlaceholders(query, accessor, queryParameterBindings); Query query = null; if (fieldSpec != null) { String fieldString = replacePlaceholders(fieldSpec, accessor, fieldSpecParameterBindings); query = new BasicQuery(queryString, fieldString); } else { query = new BasicQuery(queryString); } query.with(accessor.getSort()); if (LOG.isDebugEnabled()) { LOG.debug(String.format("Created query %s", query.getQueryObject())); } return query; }
Source:
<code>public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) { <START> final XpathFilter xpathFilter = getXpathFilter(); <END> return xpathFilter.accept(treeWalkerAuditEvent); }</code><technical_language>create filter re-use one. Accept is called for file, this unnecessary slowdown recreate instance over. Please remove getXpathFilter move code finishLocalSetup assign a field</technical_language>

Target:
public boolean accept(TreeWalkerAuditEvent treeWalkerAuditEvent) { return xpathFilter.accept(treeWalkerAuditEvent); }
Source:
<code>public void testNfsConnectionWithValidMountOptions() { <START> StorageServerConnections newPosixConnection = createConnection(StorageType.NFS, "timeo=30, validoption=666"); <END> params.setStorageServerConnection(newPosixConnection); ValidationResult result = command.validateMountOptions(); assertTrue(result.isValid()); }</code><technical_language>timeo managed..</technical_language>

Target:
public void testNfsConnectionWithValidMountOptions() { testConnectionMountOptionsValidations(StorageType.NFS, "validoption=30, anothervalidoption=666", true); }
Source:
<code>public void test_getAlwaysShowScrollBars() { boolean defaultFlag = scrolledComposite.getAlwaysShowScrollBars(); boolean setFlag = !defaultFlag; scrolledComposite.setAlwaysShowScrollBars(setFlag); <START> if (setFlag) <END> assertTrue(scrolledComposite.getAlwaysShowScrollBars()); else assertFalse(scrolledComposite.getAlwaysShowScrollBars()); setFlag = !setFlag; scrolledComposite.setAlwaysShowScrollBars(setFlag); if (setFlag) assertTrue(scrolledComposite.getAlwaysShowScrollBars()); else assertFalse(scrolledComposite.getAlwaysShowScrollBars()); scrolledComposite.setAlwaysShowScrollBars(defaultFlag); }</code><technical_language>{ } blocks please</technical_language>

Target:
public void test_getAlwaysShowScrollBars() { boolean defaultFlag = scrolledComposite.getAlwaysShowScrollBars(); boolean setFlag = !defaultFlag; scrolledComposite.setAlwaysShowScrollBars(setFlag); if (setFlag){ assertTrue(scrolledComposite.getAlwaysShowScrollBars()); } else{ assertFalse(scrolledComposite.getAlwaysShowScrollBars()); } setFlag = !setFlag; scrolledComposite.setAlwaysShowScrollBars(setFlag); if (setFlag){ assertTrue(scrolledComposite.getAlwaysShowScrollBars()); } else{ assertFalse(scrolledComposite.getAlwaysShowScrollBars()); } scrolledComposite.setAlwaysShowScrollBars(defaultFlag); }
Source:
<code>public int lookupId(String name) { <START> return name == null || "".equals(name) ? 0 : -1; <END> }</code><technical_language>For consistency, try move Strings.isNullOrEmpty, faster, .equals</technical_language>

Target:
public int lookupId(String name) { return Strings.isNullOrEmpty(name) ? 0 : -1; }
Source:
<code>public void testStartKeepaliveWLAN() throws Exception { testConnectEvent(); waitForMs(200); DataServiceManager mMockDsm = mock(DataServiceManager.class); <START> mDc.setDataServiceManager(mMockDsm); <END> doReturn(TransportType.WLAN).when(mMockDsm).getTransportType(); final int sessionHandle = 0xF00; final int slotId = 3; final int interval = 10; KeepalivePacketData kd = KeepalivePacketData.nattKeepalivePacket( NetworkUtils.numericToInetAddress("1.2.3.4"), 1234, NetworkUtils.numericToInetAddress("8.8.8.8"), 4500); mDc.obtainMessage( DataConnection.EVENT_KEEPALIVE_START_REQUEST, slotId, interval, kd).sendToTarget(); waitForMs(100); verify(mSimulatedCommandsVerifier, times(0)) .startNattKeepalive(anyInt(), eq(kd), eq(interval * 1000), any(Message.class)); }</code><technical_language>instead of creating a method setDataServiceManager, TelephonyTest's replaceInstance()</technical_language>

Target:
public void testStartKeepaliveWLAN() throws Exception { testConnectEvent(); waitForMs(200); DataServiceManager mockDsm = mock(DataServiceManager.class); replaceInstance(DataConnection.class, "mDataServiceManager", mDc, mockDsm); doReturn(TransportType.WLAN).when(mockDsm).getTransportType(); final int sessionHandle = 0xF00; final int slotId = 3; final int interval = 10; KeepalivePacketData kd = KeepalivePacketData.nattKeepalivePacket( NetworkUtils.numericToInetAddress("1.2.3.4"), 1234, NetworkUtils.numericToInetAddress("8.8.8.8"), 4500); mDc.obtainMessage( DataConnection.EVENT_KEEPALIVE_START_REQUEST, slotId, interval, kd).sendToTarget(); waitForMs(100); try { verify(mSimulatedCommandsVerifier, times(0)) .startNattKeepalive(anyInt(), eq(kd), eq(interval * 1000), any(Message.class)); } finally { restoreInstance(DataConnection.class, "mDataServiceManager", mDc); } }
Source:
<code>public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { TFM_Util.adminAction(sender.getName(), "Opping " + sender.getName(), false); sender.setOp(true); sender.sendMessage(TotalFreedomMod.YOU_ARE_OP); if (!TFM_AdminList.isAdminImpostor(sender_p)) { sender.sendMessage("You are a Imposter, You need to verify first"); sender.setOp(false); <START> sender.sendMessage(TotalFreedomMod.YOU_ARE_NOT_OP); <END> } return true; }</code><technical_language>sending OP message? op already, this need happening</technical_language>

Target:
public boolean run(CommandSender sender, Player sender_p, Command cmd, String commandLabel, String[] args, boolean senderIsConsole) { TFM_Util.adminAction(sender.getName(), "Opping " + sender.getName(), false); sender.setOp(true); sender.sendMessage(TotalFreedomMod.YOU_ARE_OP); if (!TFM_AdminList.isAdminImpostor(sender_p)) { sender.sendMessage("You are a Imposter, You need to verify first"); sender.setOp(false); } return true; }
Source:
<code>private void dragDetectedInAvailable(MouseEvent event) { <START> PreviewTabViewModel previewTabViewModel = viewModel; <END> List<PreviewLayout> selectedLayouts = new ArrayList<>(previewTabViewModel.availableSelectionModelProperty().getValue().getSelectedItems()); if (!selectedLayouts.isEmpty()) { Dragboard dragboard = startDragAndDrop(TransferMode.MOVE); previewTabViewModel.dragDetected(previewTabViewModel.availableListProperty(), selectedLayouts, dragboard); } event.consume(); }</code><technical_language>Replace (inline) previewTabViewModel viewModel</technical_language>

Target:
private void dragDetectedInAvailable(MouseEvent event) { List<PreviewLayout> selectedLayouts = new ArrayList<>(viewModel.availableSelectionModelProperty().getValue().getSelectedItems()); if (!selectedLayouts.isEmpty()) { Dragboard dragboard = startDragAndDrop(TransferMode.MOVE); viewModel.dragDetected(viewModel.availableListProperty(), selectedLayouts, dragboard); } event.consume(); }
Source:
<code>static WeekActivityDTO createInstance(WeekActivity weekActivity, LevelOfDetail levelOfDetail) { boolean includeDetail = levelOfDetail == LevelOfDetail.WeekDetail; return new WeekActivityDTO(weekActivity.getGoal().getID(), weekActivity.getStartTime(), includeIf(() -> weekActivity.getSpread(), includeDetail), <START> includeIf(() -> weekActivity.getTotalActivityDurationMinutes(), includeDetail), <END> weekActivity.getDayActivities().stream() .map(dayActivity -> DayActivityDTO.createInstance(dayActivity, levelOfDetail)) .collect(Collectors.toList())); }</code><technical_language>here: includeDetail ? weekActivity.getTotalActivitDurationMinutes() : Optional.empty()</technical_language>

Target:
static WeekActivityDTO createInstance(WeekActivity weekActivity, LevelOfDetail levelOfDetail) { boolean includeDetail = levelOfDetail == LevelOfDetail.WeekDetail; return new WeekActivityDTO(weekActivity.getGoal().getID(), weekActivity.getStartTime(), includeDetail ? weekActivity.getSpread() : Collections.emptyList(), includeDetail ? Optional.of(weekActivity.getTotalActivityDurationMinutes()) : Optional.empty(), weekActivity.getDayActivities().stream() .map(dayActivity -> DayActivityDTO.createInstance(dayActivity, levelOfDetail)) .collect(Collectors.toList())); }
Source:
<code>protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { <START> return traverseMapBySortedKeyOrder? new JacksonTraverseCallbackMapKeyOrdered(generator): new JacksonTraverseCallback(generator); <END> }</code><technical_language>space</technical_language>

Target:
protected Data.TraverseCallback createTraverseCallback(JsonGenerator generator, boolean traverseMapBySortedKeyOrder) { return new JacksonTraverseCallback(generator, traverseMapBySortedKeyOrder); }
Source:
<code>static boolean isSingleItem(final Memory mem) { final boolean preLongs = extractPreLongs(mem) == 1; final boolean serVer = extractSerVer(mem) >= 3; <START> final boolean famId = extractFamilyID(mem) == 3; END> final boolean flags = (extractFlags(mem) & 0x1F) == 0x1A; return preLongs && serVer && famId && flags; }</code><technical_language>this refer a constant defined in Family</technical_language>

Target:
static boolean isSingleItem(final Memory mem) { final boolean preLongs = extractPreLongs(mem) == 1; final boolean serVer = extractSerVer(mem) >= 3; final boolean famId = extractFamilyID(mem) == Family.COMPACT.getID(); final boolean flags = (extractFlags(mem) & 0x1F) == 0x1A; return preLongs && serVer && famId && flags; }
Source:
<code><START> public void setRefSpecs(RefSpec... specs) { <END> this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); }</code><technical_language>Missing checkCallable(). a variant takes Collection too</technical_language>

Target:
public FetchCommand setRefSpecs(RefSpec... specs) { checkCallable(); this.refSpecs.clear(); for (RefSpec spec : specs) refSpecs.add(spec); return this; }
Source:
<code>public Boolean ChangeState(String deviceId, Boolean newStateIsOn) { Reader reader = null; logger.debug( "Change state for device id '{}', new state is on: '{}'", deviceId, newStateIsOn); try { HttpURLConnection httpURLConnection; <START> httpURLConnection = (HttpURLConnection) new URL(API_URL + "device/switch" + <END> "?authToken=" + this.authToken + "&id=" + deviceId + "&on=" + newStateIsOn.toString()) .openConnection(); InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if(!status.equals("ok")){ String error = jsonObject.get("error").getAsString(); logger.error("Unable to switch state for device '{}' error '{}'", deviceId, error); return false; } String newState = jsonObject.get("state").getAsString(); logger.debug( "Switch state for device '{}' successfull, state is '{}'", deviceId, newState); return true; } catch(Exception ex) { logger.error("Error set state: '{}'", ex.toString()); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }</code><technical_language>please assign URL a local variable opening connection? This helps while debugging problems</technical_language>

Target:
public Boolean ChangeState(String deviceId, Boolean newStateIsOn) { Reader reader = null; logger.debug("Change state for device id '{}', new state is on: '{}'", deviceId, newStateIsOn); try { String url = API_URL + "device/switch" + "?authToken=" + this.authToken + "&id=" + deviceId + "&on=" + newStateIsOn.toString(); HttpURLConnection httpURLConnection; httpURLConnection = (HttpURLConnection) new URL(url) .openConnection(); InputStream inputStream = httpURLConnection.getInputStream(); reader = new InputStreamReader(inputStream, "UTF-8"); JsonObject jsonObject = (JsonObject) jsonParser.parse(reader); String status = jsonObject.get("status").getAsString(); if (!status.equals("ok")) { String error = jsonObject.get("error").getAsString(); logger.error( "Unable to switch state for device '{}' error '{}'", deviceId, error); return false; } String newState = jsonObject.get("state").getAsString(); logger.debug( "Switch state for device '{}' successfull, state is '{}'", deviceId, newState); return true; } catch (Exception ex) { logger.error("Error set state: '{}'", ex.toString()); return false; } finally { if (reader != null) { try { reader.close(); } catch (IOException ignored) { } } } }
Source:
<code>public String decode(String encodedData) { String decodedData = ""; Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z\\s]"); Matcher matcher = pattern.matcher(encodedData); while (matcher.find()) { try { int number = Integer.parseInt(matcher.group()); matcher.find(); <START> while (number-- != 0) { <END> decodedData += matcher.group(); } } catch (NumberFormatException e) { decodedData += matcher.group(); } } return decodedData; }</code><technical_language>short neat, changing of a variable in statment comparing easily get confusing. I recommend a for loop (e.g. for (; number > 0; number--)) decrementing variable while loop</technical_language>

Target:
public String decode(String encodedData) { StringBuilder decodedData = new StringBuilder(); Pattern pattern = Pattern.compile("[0-9]+|[a-zA-Z\\s]"); Matcher matcher = pattern.matcher(encodedData); while (matcher.find()) { try { int number = Integer.parseInt(matcher.group()); matcher.find(); for (int i = 0; i<number; i++) { decodedData.append(matcher.group()); } } catch (NumberFormatException e) { decodedData.append(matcher.group()); } } return decodedData.toString(); }