auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void process(Tuple tuple) { try { LOG.debug("Processing Tuple: {}", tuple); SolrRequest request = solrMapper.toSolrRequest(tuple); solrClient.request(request, solrMapper.getCollection()); ack(tuple); LOG.debug("Acked Tuple: {}", tuple); } catch (Exception e) { fail(tuple, e); LOG.debug("Failed Tuple: {}", tuple, e); } }

Target:
protected void process(Tuple tuple) { try { SolrRequest request = solrMapper.toSolrRequest(tuple); solrClient.request(request, solrMapper.getCollection()); ack(tuple); } catch (Exception e) { fail(tuple, e); } }
Source:
protected Optional<PlanNodeStatsEstimate> doCalculate(SpatialJoinNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate leftStats = sourceStats.getStats(node.getLeft()); PlanNodeStatsEstimate rightStats = sourceStats.getStats(node.getRight()); PlanNodeStatsEstimate crossJoinStats = crossJoinStats(node, leftStats, rightStats); switch (node.getType()) { case INNER: return Optional.of(filterStatsCalculator.filterStats(crossJoinStats, node.getFilter(), session, types)); case LEFT: return Optional.of(UNKNOWN_STATS); default: throw new IllegalStateException("Unknown spatial join type: " + node.getType()); } }

Target:
protected Optional<PlanNodeStatsEstimate> doCalculate(SpatialJoinNode node, StatsProvider sourceStats, Lookup lookup, Session session, TypeProvider types) { PlanNodeStatsEstimate leftStats = sourceStats.getStats(node.getLeft()); PlanNodeStatsEstimate rightStats = sourceStats.getStats(node.getRight()); PlanNodeStatsEstimate crossJoinStats = crossJoinStats(node, leftStats, rightStats); switch (node.getType()) { case INNER: return Optional.of(statsCalculator.filterStats(crossJoinStats, node.getFilter(), session, types)); case LEFT: return Optional.of(UNKNOWN_STATS); default: throw new IllegalArgumentException("Unknown spatial join type: " + node.getType()); } }
Source:
public static boolean downloadUpdatedBlob(Map<String, Object> conf, BlobStore blobStore, String key, Set<NimbusInfo> nimbusInfos) throws TTransportException { ClientBlobStore remoteBlobStore; AtomicOutputStream out = null; boolean isSuccess = false; LOG.debug("Download blob NimbusInfos {}", nimbusInfos); for (NimbusInfo nimbusInfo : nimbusInfos) { if (isSuccess) { break; } try (NimbusClient client = new NimbusClient(conf, nimbusInfo.getHost(), nimbusInfo.getPort(), null)) { remoteBlobStore = new NimbusBlobStore(); remoteBlobStore.setClient(conf, client); try (InputStreamWithMeta in = remoteBlobStore.getBlob(key)) { out = blobStore.updateBlob(key, getNimbusSubject()); byte[] buffer = new byte[2048]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } if (out != null) { out.close(); } isSuccess = true; } catch(FileNotFoundException fnf) { LOG.warn("Blobstore file for key '{}' does not exist or got deleted before it could be downloaded.", key, fnf); } catch (IOException | AuthorizationException exception) { throw new RuntimeException(exception); } catch (KeyNotFoundException knf) { LOG.info("KeyNotFoundException", knf); } catch (Exception exp) { LOG.error("Exception", exp); } finally { if (null != out) { try { out.cancel(); } catch (IOException e) { } } } } if (!isSuccess) { LOG.error("Could not update the blob with key: {}", key); } return isSuccess; }

Target:
public static boolean downloadUpdatedBlob(Map<String, Object> conf, BlobStore blobStore, String key, Set<NimbusInfo> nimbusInfos) throws TTransportException { ClientBlobStore remoteBlobStore; AtomicOutputStream out = null; boolean isSuccess = false; LOG.debug("Download blob NimbusInfos {}", nimbusInfos); for (NimbusInfo nimbusInfo : nimbusInfos) { if (isSuccess) { break; } try (NimbusClient client = new NimbusClient(conf, nimbusInfo.getHost(), nimbusInfo.getPort(), null)) { remoteBlobStore = new NimbusBlobStore(); remoteBlobStore.setClient(conf, client); try (InputStreamWithMeta in = remoteBlobStore.getBlob(key)) { out = blobStore.updateBlob(key, getNimbusSubject()); byte[] buffer = new byte[2048]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.close(); out = null; } isSuccess = true; } catch(FileNotFoundException fnf) { LOG.warn("Blobstore file for key '{}' does not exist or got deleted before it could be downloaded.", key, fnf); } catch (IOException | AuthorizationException exception) { throw new RuntimeException(exception); } catch (KeyNotFoundException knf) { LOG.info("KeyNotFoundException", knf); } catch (Exception exp) { LOG.error("Exception", exp); } finally { if (out != null) { try { out.cancel(); } catch (IOException e) { } } } } if (!isSuccess) { LOG.error("Could not update the blob with key: {}", key); } return isSuccess; }
Source:
public void start(List<TaskSource> sources) { requireNonNull(sources, "sources is null"); scheduleDriversForTaskLifeCycle(); scheduleDriversForSplitLifeCycle(sources); checkTaskCompletion(); }

Target:
public void start(List<TaskSource> sources) { requireNonNull(sources, "sources is null"); checkState(started.compareAndSet(false, true), "already started"); scheduleDriversForTaskLifeCycle(); scheduleDriversForSplitLifeCycle(sources); checkTaskCompletion(); }
Source:
public void testBug475357_IconChanges() throws Exception { part1.getTransientData().put(SWTPartRenderer.ICON_URI_FOR_PART, PART_DESC_ICON); part1.setIconURI(PART_DESC_ICON); CTabItem item = ((CTabFolder) partStack.getWidget()).getItem(0); assertEquals(PART_DESC_ICON, part1.getTransientData().get(SWTPartRenderer.ICON_URI_FOR_PART)); assertEquals(8, item.getImage().getImageData().width); part1.setIconURI(PART_ICON); assertEquals(PART_ICON, part1.getTransientData().get(SWTPartRenderer.ICON_URI_FOR_PART)); assertEquals(16, item.getImage().getImageData().width); }

Target:
public void testBug475357_IconChanges() throws Exception { part1.setIconURI(PART_DESC_ICON); CTabItem item = ((CTabFolder) partStack.getWidget()).getItem(0); assertEquals(PART_DESC_ICON, part1.getTransientData().get(SWTPartRenderer.ICON_URI_FOR_PART)); assertEquals(8, item.getImage().getImageData().width); part1.setIconURI(PART_ICON); assertEquals(PART_ICON, part1.getTransientData().get(SWTPartRenderer.ICON_URI_FOR_PART)); assertEquals(16, item.getImage().getImageData().width); }
Source:
protected void addVmTemplateImages(Map<Guid, Guid> srcDeviceIdToTargetDeviceIdMapping) { Guid vmSnapshotId = Guid.newGuid(); for (DiskImage diskImage : mImages) { VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, buildChildCommandParameters(diskImage, vmSnapshotId), cloneContextAndDetachFromParent()); if (!retValue.getSucceeded()) { throw new VdcBLLException(retValue.getFault().getError(), retValue.getFault().getMessage()); } getReturnValue().getVdsmTaskIdList().addAll(retValue.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) retValue.getActionReturnValue(); srcDeviceIdToTargetDeviceIdMapping.put(diskImage.getId(), newImage.getId()); } }

Target:
protected void addVmTemplateImages(Map<Guid, Guid> srcDeviceIdToTargetDeviceIdMapping) { for (DiskImage diskImage : mImages) { VdcReturnValueBase retValue = Backend.getInstance().runInternalAction( VdcActionType.CreateImageTemplate, buildChildCommandParameters(diskImage, Guid.newGuid()), ExecutionHandler.createDefaultContextForTasks(getContext())); if (!retValue.getSucceeded()) { throw new VdcBLLException(retValue.getFault().getError(), retValue.getFault().getMessage()); } getReturnValue().getVdsmTaskIdList().addAll(retValue.getInternalVdsmTaskIdList()); DiskImage newImage = (DiskImage) retValue.getActionReturnValue(); srcDeviceIdToTargetDeviceIdMapping.put(diskImage.getId(), newImage.getId()); } }
Source:
public void adminStopAll() throws IOException { String master = getHosts(MASTER_HOSTS_FILE).get(0); String[] cmd = new String[] {SUDO_CMD, "-u", user, accumuloPath, Admin.class.getName(), "stopAll"}; Entry<Integer,String> pair = exec(master, cmd); if (0 != pair.getKey().intValue()) { throw new IOException("stopAll did not finish successfully, retcode=" + pair.getKey() + ", stdout=" + pair.getValue()); } }

Target:
public void adminStopAll() throws IOException { String master = getHosts(MASTER_HOSTS_FILE).get(0); String[] cmd = new String[] {serverCmdPrefix, accumuloPath, Admin.class.getName(), "stopAll"}; Entry<Integer,String> pair = exec(master, cmd); if (0 != pair.getKey().intValue()) { throw new IOException("stopAll did not finish successfully, retcode=" + pair.getKey() + ", stdout=" + pair.getValue()); } }
Source:
public void parsesInvalidFirstNameField() throws IOException { final MemberProfileJson memberprofilejson = Mockito.mock(MemberProfileJson.class); Mockito.when( memberprofilejson.fetch( Mockito.anyString(), Mockito.anyString(), Mockito.any(Href.class) ) ).thenReturn( Json.createReader( new FileInputStream( PsLinkedinTest.class.getResource( "linkedinTestUserInvalidFirstName.json" ).getPath() ) ).readObject() ); MatcherAssert.assertThat( new PsLinkedin(memberprofilejson) .enter(REQUEST).next() .properties().get("first_name"), Matchers.is("?") ); }

Target:
public void parsesInvalidFirstNameField() throws IOException { MatcherAssert.assertThat( new PsLinkedin( this.mockRequest( "linkedinTestUserInvalidFirstName.json" ), "app", "key" ).enter(REQUEST).next().properties().get("first_name"), Matchers.is("?") ); }
Source:
public String apply(String dimValue) { if (dimValue == null) return null; Matcher matcher = pattern.matcher(dimValue); return matcher.find() ? dimValue : null; }

Target:
public String apply(String dimValue) { dimValue = (dimValue == null) ? "" : dimValue; Matcher matcher = pattern.matcher(dimValue); return matcher.find() ? dimValue : null; }
Source:
public ASTNode transform(RuleAutomatonDisjunction ruleAutomatonDisjunction) { return new RuleAutomatonDisjunction( ruleAutomatonDisjunction.disjunctions().stream() .map(p -> Pair.of((Term) p.getLeft().accept(this), p.getRight())) .collect(Collectors.toList()), context); }

Target:
public ASTNode transform(RuleAutomatonDisjunction ruleAutomatonDisjunction) { List<Pair<Term, BitSet>> children = ruleAutomatonDisjunction.disjunctions().stream() .map(p -> Pair.of((Term) p.getLeft().accept(this), p.getRight())) .collect(Collectors.toList()); if (children.equals(ruleAutomatonDisjunction.disjunctions())) { return ruleAutomatonDisjunction; } else { return new RuleAutomatonDisjunction( children, context); } }
Source:
private String getMetadataFromDigitalDocument(MetadataLevel inLevel, String metadata) { if (this.dd != null) { DocStructInterface topstruct = this.dd.getLogicalDocStruct(); DocStructInterface firstchildstruct = null; if (topstruct.getAllChildren() != null && topstruct.getAllChildren().size() > 0) { firstchildstruct = topstruct.getAllChildren().get(0); } MetadataTypeInterface mdt; try { mdt = UghHelper.getMetadataType(this.prefs, metadata); } catch (UghHelperException e) { logger.error(e.getMessage(), e); Helper.setFehlerMeldung(e); return ""; } String result = ""; String resultTop = getMetadataValue(topstruct, mdt); String resultFirst = null; if (firstchildstruct != null) { resultFirst = getMetadataValue(firstchildstruct, mdt); } switch (inLevel) { case FIRSTCHILD: if (resultFirst == null) { logger.info("Can not replace firstChild-variable for METS: {}", metadata); result = ""; } else { result = resultFirst; } break; case TOPSTRUCT: if (resultTop == null) { result = ""; logger.warn("Can not replace topStruct-variable for METS: {}", metadata); } else { result = resultTop; } break; case ALL: if (resultFirst != null) { result = resultFirst; } else if (resultTop != null) { result = resultTop; } else { result = ""; logger.warn("Can not replace variable for METS: {}", metadata); } break; default: break; } return result; } else { return ""; } }

Target:
private String getMetadataFromDigitalDocument(MetadataLevel inLevel, String metadata) { if (this.dd != null) { DocStructInterface topstruct = this.dd.getLogicalDocStruct(); DocStructInterface firstchildstruct = null; if (topstruct.getAllChildren() != null && topstruct.getAllChildren().size() > 0) { firstchildstruct = topstruct.getAllChildren().get(0); } MetadataTypeInterface mdt; try { mdt = UghHelper.getMetadataType(this.prefs, metadata); } catch (UghHelperException e) { Helper.setErrorMessage(e.toString(), logger, e); return ""; } String result = ""; String resultTop = getMetadataValue(topstruct, mdt); String resultFirst = null; if (firstchildstruct != null) { resultFirst = getMetadataValue(firstchildstruct, mdt); } switch (inLevel) { case FIRSTCHILD: if (resultFirst == null) { logger.info("Can not replace firstChild-variable for METS: {}", metadata); result = ""; } else { result = resultFirst; } break; case TOPSTRUCT: if (resultTop == null) { result = ""; logger.warn("Can not replace topStruct-variable for METS: {}", metadata); } else { result = resultTop; } break; case ALL: if (resultFirst != null) { result = resultFirst; } else if (resultTop != null) { result = resultTop; } else { result = ""; logger.warn("Can not replace variable for METS: {}", metadata); } break; default: break; } return result; } else { return ""; } }
Source:
public void testIssue445() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(100); final int maxCallables = 10_000; List<Callable<String>> callableList = new ArrayList<>(maxCallables); for (int i = 0; i < maxCallables; i++) { callableList.add(new Callable<String>() { @Override public String call() throws Exception { MyInfluxDBBean myBean = new MyInfluxDBBean(); return myBean.connectAndDoNothing1(); } }); } System.out.println("Invoking all callableList (size()=" + callableList.size() + ")"); executor.invokeAll(callableList); System.out.println("Shutting down..."); executor.shutdown(); System.out.println("Shutdown requested and waiting for termination..."); if (!executor.awaitTermination(20, TimeUnit.SECONDS)) { executor.shutdownNow(); } Assertions.assertTrue(MyInfluxDBBean.OK); Assertions.assertTrue(MyInfluxDBBean.OKHTTP_BUILDER.interceptors().isEmpty()); }

Target:
public void testIssue445() throws InterruptedException { ExecutorService executor = Executors.newFixedThreadPool(100); final int maxCallables = 10_000; List<Callable<String>> callableList = new ArrayList<>(maxCallables); for (int i = 0; i < maxCallables; i++) { callableList.add(new Callable<String>() { @Override public String call() throws Exception { MyInfluxDBBean myBean = new MyInfluxDBBean(); return myBean.connectAndDoNothing1(); } }); } executor.invokeAll(callableList); executor.shutdown(); if (!executor.awaitTermination(20, TimeUnit.SECONDS)) { executor.shutdownNow(); } Assertions.assertTrue(MyInfluxDBBean.OK); Assertions.assertTrue(MyInfluxDBBean.OKHTTP_BUILDER.interceptors().isEmpty()); }
Source:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain; try { domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); domain.destroy(); fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { } }

Target:
public void shouldNotDeleteDomainWithApplications() throws OpenShiftException { IDomain domain = null; try { domain = DomainTestUtils.ensureHasDomain(user); ApplicationTestUtils.getOrCreateApplication(domain); assertThat(domain.getApplications()).isNotEmpty(); domain.destroy(); fail("OpenShiftEndpointException did not occur"); } catch (OpenShiftEndpointException e) { } }
Source:
private Optional<ComponentModel> findTestConnectionGlobalElementFrom(List<ComponentModel> globalElementsComponentModel, ExtensionModelHelper extensionModelHelper) { final List<ComponentModel> testConnectionComponentModels_new = globalElementsComponentModel .stream() .filter(globalElementComponentModel -> globalElementComponentModel.getModel(ConfigurationModel.class) .map(configurationModel -> configurationModel.getConnectionProviders().stream() .anyMatch(ConnectionProviderModel::supportsConnectivityTesting)) .orElse(false)) .collect(toList()); if (testConnectionComponentModels_new.size() > 1) { throw new MuleRuntimeException(createStaticMessage(format("There are [%d] global elements that can be potentially used for test connection when it should be just one. Mark any of them with the attribute [%s=\"true\"], offended global elements are: [%s]", testConnectionComponentModels_new.size(), MODULE_CONNECTION_MARKER_ATTRIBUTE, testConnectionComponentModels_new.stream() .map(ComponentModel::getNameAttribute) .sorted() .collect(joining(", "))))); } return testConnectionComponentModels_new.stream().findFirst(); }

Target:
private Optional<ComponentModel> findTestConnectionGlobalElementFrom(List<ComponentModel> globalElementsComponentModel, ExtensionModelHelper extensionModelHelper) { final List<ComponentModel> testConnectionComponentModels = globalElementsComponentModel .stream() .filter(globalElementComponentModel -> globalElementComponentModel.getModel(ConfigurationModel.class) .map(configurationModel -> configurationModel.getConnectionProviders().stream() .anyMatch(ConnectionProviderModel::supportsConnectivityTesting)) .orElse(false)) .collect(toList()); if (testConnectionComponentModels.size() > 1) { throw new MuleRuntimeException(createStaticMessage(format("There are [%d] global elements that can be potentially used for test connection when it should be just one. Mark any of them with the attribute [%s=\"true\"], offended global elements are: [%s]", testConnectionComponentModels.size(), MODULE_CONNECTION_MARKER_ATTRIBUTE, testConnectionComponentModels.stream() .map(ComponentModel::getNameAttribute) .sorted() .collect(joining(", "))))); } return testConnectionComponentModels.stream().findFirst(); }
Source:
public static WifiSsid createFromByteArray(byte ssid[]) { WifiSsid wifiSsid = new WifiSsid(); wifiSsid.octets.write(ssid, 0 , ssid.length);; return wifiSsid; }

Target:
public static WifiSsid createFromByteArray(byte ssid[]) { WifiSsid wifiSsid = new WifiSsid(); if (ssid != null) { wifiSsid.octets.write(ssid, 0 , ssid.length);; } return wifiSsid; }
Source:
public String getCreateQuery(String tableName, Collection<SinkRecordField> fields) { String createQuery = super.getCreateQuery(tableName, fields).replace("CREATE TABLE", "CREATE COLUMN TABLE"); log.trace("Create Query : " + createQuery); return createQuery; }

Target:
public String getCreateQuery(String tableName, Collection<SinkRecordField> fields) { return super.getCreateQuery(tableName, fields).replace("CREATE TABLE", "CREATE COLUMN TABLE"); }
Source:
public void initialize(final AppStateManager stateManager, final Application app) { super.initialize(stateManager, app); this.app = (Main) app; rootNode = this.app.getRootNode(); assetManager = this.app.getAssetManager(); this.stateManager = this.app.getStateManager(); inputManager = this.app.getInputManager(); viewPort = this.app.getViewPort(); SingleBarLoadingState loader = new SingleBarLoadingState() { @Override public Void onLoad() { try { if (level != null) { kwdFile = new KwdFile(Main.getDkIIFolder(), new File(Main.getDkIIFolder().concat(AssetsConverter.MAPS_FOLDER.concat(level).concat(".kwd")))); } else { kwdFile.load(); } setProgress(0.25f); worldNode = new Node("World"); worldNode.attachChild(new MapLoader() { @Override protected void updateProgress(int progress, int max) { setProgress(0.25f + ((float) progress / max * 0.75f)); } }.load(assetManager, kwdFile)); bulletAppState = new BulletAppState(); this.stateManager.attach(bulletAppState); rootNode.attachChild(new ThingLoader().load(bulletAppState, assetManager, kwdFile)); setProgress(1.0f); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load the game!", e); } return null; } @Override public void onLoadComplete() { GameState.this.app.setViewProcessors(); rootNode.attachChild(worldNode); stateManager.getState(PlayerState.class).setEnabled(true); } }; stateManager.attach(loader); }

Target:
public void initialize(final AppStateManager stateManager, final Application app) { super.initialize(stateManager, app); this.app = (Main) app; rootNode = this.app.getRootNode(); assetManager = this.app.getAssetManager(); this.stateManager = this.app.getStateManager(); inputManager = this.app.getInputManager(); viewPort = this.app.getViewPort(); SingleBarLoadingState loader = new SingleBarLoadingState() { @Override public Void onLoad() { try { if (level != null) { kwdFile = new KwdFile(Main.getDkIIFolder(), new File(Main.getDkIIFolder().concat(AssetsConverter.MAPS_FOLDER.concat(level).concat(".kwd")))); } else { kwdFile.load(); } setProgress(0.25f); worldNode = new Node("World"); worldNode.attachChild(new MapLoader() { @Override protected void updateProgress(int progress, int max) { setProgress(0.25f + ((float) progress / max * 0.75f)); } }.load(assetManager, kwdFile)); bulletAppState = new BulletAppState(); this.stateManager.attach(bulletAppState); worldNode.attachChild(new ThingLoader().load(bulletAppState, assetManager, kwdFile)); setProgress(1.0f); } catch (Exception e) { logger.log(Level.SEVERE, "Failed to load the game!", e); } return null; } @Override public void onLoadComplete() { GameState.this.app.setViewProcessors(); rootNode.attachChild(worldNode); stateManager.getState(PlayerState.class).setEnabled(true); } }; stateManager.attach(loader); }
Source:
synchronized Set<String> metadataTopics() { Set<String> topics = new HashSet<>(groupSubscription); topics.addAll(subscription); return topics; }

Target:
synchronized Set<String> metadataTopics() { return groupSubscription.isEmpty() ? subscription : groupSubscription; }
Source:
public Set<Stream> getResultStreams() { Set<Stream> streams = new HashSet<Stream>(); streams.add(this.modelResultStream); streams.add(this.rootResultStream); return streams; }

Target:
public Set<Stream> getResultStreams() { Set<Stream> streams = ImmutableSet.of(this.modelResultStream,this.rootResultStream); return streams; }
Source:
private void enableBreakpoints() { for (BreakpointRequest fBreakpointRequest : fBreakpointRequests) { fBreakpointRequest.enable(); } }

Target:
private void enableBreakpoints() { for (BreakpointRequest breakpointRequest : fBreakpointRequests) { breakpointRequest.enable(); } }
Source:
public void addGunner(Person p) { addGunner(Objects.requireNonNull(p), false); }

Target:
public void addGunner(Person p) { addGunner(p, false); }
Source:
public BaseWorkerTask<Operation> createBaseWorker() { return new BaseWorkerTask<Operation>() { @Override protected OperationSelector<Operation> createOperationSelector() { return new OperationSelector<Operation>().addOperation(Operation.PUT, putProb) .addOperationRemainingProbability(Operation.GET); } @Override protected void doRun(Operation operation) { int key = randomKey(); switch (operation) { case PUT: int value = randomValue(); putLatency.started(); if (useSet) { map.set(key, value); } else { map.put(key, value); } putLatency.done(); break; case GET: getLatency.started(); map.get(key); getLatency.done(); break; default: throw new UnsupportedOperationException(); } throughput.done(); } private int randomKey() { return keys[nextInt(keys.length)]; } private int randomValue() { return nextInt(Integer.MAX_VALUE); } }; }

Target:
public AbstractWorkerTask<Operation> createBaseWorker() { return new WorkerTask(); }
Source:
private File cropImageFile(File selectedFile){ int targetImageWidth = 100; int targetImageHeight = 100; File imageFile = null; try { BufferedImage avatarImageBuffered = ImageIO.read(selectedFile); BufferedImage croppedImage; int currentImageWidth = avatarImageBuffered.getWidth(null); int currentImageHeight = avatarImageBuffered.getHeight(null); if(currentImageHeight == targetImageHeight && currentImageWidth == targetImageHeight){ croppedImage = avatarImageBuffered; imageFile = selectedFile; }else{ double targetImageRatio = (double)targetImageWidth / (double)targetImageHeight; if (currentImageWidth < targetImageRatio * currentImageHeight) { currentImageHeight = new Double((new Double(currentImageWidth )/ new Double(targetImageRatio))).intValue(); } else { currentImageWidth = new Double(((double)currentImageHeight * targetImageRatio)).intValue(); } imageFile = new File(SparkManager.getUserDirectory(), "personal.png"); croppedImage = Thumbnails.of(avatarImageBuffered).sourceRegion(Positions.CENTER, currentImageWidth, currentImageHeight). size(targetImageWidth,targetImageWidth).asBufferedImage(); ImageIO.write(croppedImage, "PNG", imageFile); } }catch (IOException ex){ ex.printStackTrace(); } return imageFile; }

Target:
private BufferedImage cropImageFile(File selectedFile) { int targetImageWidth = 64; int targetImageHeight = 64; BufferedImage croppedImage = null; try { BufferedImage avatarImageBuffered = ImageIO.read(selectedFile); int currentImageWidth = avatarImageBuffered.getWidth(null); int currentImageHeight = avatarImageBuffered.getHeight(null); if (currentImageHeight == targetImageHeight && currentImageWidth == targetImageHeight) { croppedImage = avatarImageBuffered; } else { double targetImageRatio = (double)targetImageWidth / (double)targetImageHeight; if (currentImageWidth < targetImageRatio * currentImageHeight) { currentImageHeight = new Double((double)currentImageWidth / (double)targetImageRatio).intValue(); } else { currentImageWidth = new Double(((double)currentImageHeight * targetImageRatio)).intValue(); } croppedImage = Thumbnails.of(avatarImageBuffered).sourceRegion(Positions.CENTER, currentImageWidth, currentImageHeight). size(targetImageWidth, targetImageHeight).asBufferedImage(); } } catch (IOException ex) { Log.error(ex); } return croppedImage; }
Source:
protected void run() throws Exception { StoredConfig dbconfig = db.getConfig(); RemoteConfig remoteConfig = new RemoteConfig(dbconfig, remote); PubSubConfig pubsubConfig = SubscribeDaemon.getConfig(); URIish uriish = remoteConfig.getURIs().get(0); String uriRoot = PubSubConfig.getUriRoot(uriish); String dir = db.getDirectory().getAbsolutePath(); if (uriish != null) { Publisher p = pubsubConfig.getPublisher(uriRoot); if (p == null || !p.removeSubscriber(remote, dir)) { out.println(MessageFormat.format( CLIText.get().doesNotExist, remote)); return; } if (p.getSubscribers().size() == 0) pubsubConfig.removePublisher(p); try { SubscribeDaemon.updateConfig(pubsubConfig); } catch (IOException e) { out.println(MessageFormat.format(CLIText.get().cannotWrite, SubscribeDaemon.getConfigFile())); return; } } }

Target:
protected void run() throws Exception { StoredConfig dbconfig = db.getConfig(); RemoteConfig remoteConfig = new RemoteConfig(dbconfig, remote); PubSubConfig pubsubConfig = SubscribeDaemon.getConfig(); List<URIish> uris = remoteConfig.getURIs(); if (uris.isEmpty()) { out.println(MessageFormat.format( CLIText.get().noRemoteUriUnsubscribe, remote)); return; } String uriRoot = PubSubConfig.getUriRoot(uris.get(0)); String dir = db.getDirectory().getAbsolutePath(); Publisher p = pubsubConfig.getPublisher(uriRoot); if (p == null || !p.removeSubscriber(remote, dir)) { out.println(MessageFormat.format( CLIText.get().subscriptionDoesNotExist, remote)); return; } if (p.getSubscribers().size() == 0) pubsubConfig.removePublisher(p); try { SubscribeDaemon.updateConfig(pubsubConfig); } catch (IOException e) { out.println(MessageFormat.format(CLIText.get().cannotWrite, SubscribeDaemon.getConfigFile())); return; } out.println(MessageFormat.format( CLIText.get().didUnsubscribe, remote, uriRoot)); }
Source:
private static void checkDictionary(UnpackingExpression unpackingExpression, Map<String, List<Tree>> passedParameters) { List<String> dictionaryKeys = extractKeysFromDictionary(unpackingExpression); for (String key : dictionaryKeys) { passedParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(unpackingExpression); } }

Target:
private static void checkDictionary(UnpackingExpression unpackingExpression, Map<String, List<Tree>> passedParameters) { Set<String> dictionaryKeys = extractKeysFromDictionary(unpackingExpression); dictionaryKeys.forEach(key -> passedParameters.computeIfAbsent(key, k -> new ArrayList<>()).add(unpackingExpression)); }
Source:
private static void check(@NotNull GoNamedElement element, @NotNull ProblemsHolder holder) { ProgressManager.checkCanceled(); GoFile builtin = GoSdkUtil.findBuiltinFile(element); if (builtin == null) return; String name = element.getName(); if (name == null || "Type".equals(name)) return; for (GoTypeSpec builtinTypeDeclaration : builtin.getTypes()) { if (name.equals(builtinTypeDeclaration.getName())) { registerProblem(holder, element, builtinTypeDeclaration); break; } } }

Target:
private static void check(@NotNull GoNamedElement element, @NotNull ProblemsHolder holder) { GoFile builtin = GoSdkUtil.findBuiltinFile(element); if (builtin == null) return; String name = element.getName(); if (name == null || GoTypeReference.DOC_ONLY_TYPES.contains(name)) return; for (GoTypeSpec builtinTypeDeclaration : builtin.getTypes()) { if (name.equals(builtinTypeDeclaration.getName())) { registerProblem(holder, element, builtinTypeDeclaration); return; } } ProgressManager.checkCanceled(); for (GoFunctionDeclaration builtinFunctionsDeclaration : builtin.getFunctions()) { if (name.equals(builtinFunctionsDeclaration.getName())) { registerProblem(holder, element, builtinFunctionsDeclaration); return; } } }
Source:
private void deserializeShuffle(final String serializedShuffle) { try { final Injector injector = rootInjector.forkInjector(confSerializer.fromString(serializedShuffle)); injector.getInstance(TupleNetworkSetup.class); final Shuffle shuffle = injector.getInstance(Shuffle.class); shuffleMap.put(shuffle.getShuffleDescription().getShuffleName(), shuffle); } catch (final Exception e) { throw new RuntimeException("An exception occurred while deserializing shuffle : " + serializedShuffle, e); } }

Target:
private void deserializeShuffle(final String serializedShuffle) { try { final Injector injector = rootInjector.forkInjector(confSerializer.fromString(serializedShuffle)); final Shuffle shuffle = injector.getInstance(Shuffle.class); shuffleMap.put(shuffle.getShuffleDescription().getShuffleName(), shuffle); } catch (final Exception e) { throw new RuntimeException("An exception occurred while deserializing shuffle : " + serializedShuffle, e); } }
Source:
private static void initializeFiles() throws IOException { TEST_DIR = createTempDir().toString(); DATA_FILE_PATH = Paths.get(TEST_DIR, DATA_FILE); TEST_PATH = Paths.get(TEST_DIR, NON_EXISTENT_FILE); File testInputFile = new File(TEST_DIR, DATA_FILE); if (!testInputFile.exists()) { testInputFile.createNewFile(); } FileWriter fw = new FileWriter(testInputFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(TEST_FILE_DATA); bw.close(); }

Target:
private void initializeFiles() throws IOException { testDir = Files.createTempDirectory("testDir").toString(); dataFilePath = Paths.get(testDir, DATA_FILE); testPath = Paths.get(testDir, NON_EXISTENT_FILE); File testInputFile = new File(testDir, DATA_FILE); if (!testInputFile.exists()) { testInputFile.createNewFile(); } FileWriter fw = new FileWriter(testInputFile.getAbsoluteFile()); BufferedWriter bw = new BufferedWriter(fw); bw.write(TEST_FILE_DATA); bw.close(); }
Source:
private void showSuccessToast(String wikiItemName) { String title = wikiItemName; String successStringTemplate = context.getString(R.string.successful_wikidata_edit); String successMessage = String.format(Locale.getDefault(), successStringTemplate, title); ViewUtil.showLongToast(context, successMessage); }

Target:
private void showSuccessToast(String wikiItemName) { String successStringTemplate = context.getString(R.string.successful_wikidata_edit); String successMessage = String.format(Locale.getDefault(), successStringTemplate, wikiItemName); ViewUtil.showLongToast(context, successMessage); }
Source:
public DirectoryProperty getOutputLocation() { return null; }

Target:
public DirectoryProperty getOutputLocation() { return outputLocation; }
Source:
public InputStream getContents() throws CoreException { try { return open(); } catch (IOException e) { throw new CoreException(new Status(IStatus.ERROR, path, NLS.bind( CoreText.BlobStorage_errorReadingBlob, blobId), e)); } }

Target:
public InputStream getContents() throws CoreException { try { return open(); } catch (IOException e) { throw new CoreException(Activator.error( NLS.bind(CoreText.BlobStorage_errorReadingBlob, blobId .name(), path), e)); } }
Source:
public void testRemoveSessionByUserId() throws Exception { UserSession session = createUserSession(); String ser = BridgeObjectMapper.get().writeValueAsString(session); when(jedisOps.get(USER_ID_TO_SESSION.toString())).thenReturn(ser); cacheProvider.removeSessionByUserId(USER_ID); verify(transaction).del(TOKEN_TO_USER_ID.toString()); verify(transaction).del(USER_ID_TO_SESSION.toString()); verify(transaction).exec(); }

Target:
public void testRemoveSessionByUserId() throws Exception { UserSession session = createUserSession(); String ser = BridgeObjectMapper.get().writeValueAsString(session); when(jedisOps.get(USER_ID_TO_SESSION.toString())).thenReturn(ser); cacheProvider.removeSessionByUserId(USER_ID); verify(transaction).del(TOKEN_TO_USER_ID.toString()); verify(transaction).del(USER_ID_TO_SESSION.toString()); verify(transaction).del(CacheKey.session(DECRYPTED_SESSION_TOKEN).toString()); verify(transaction).del(CacheKey.sessionByUserId(USER_ID).toString()); verify(transaction).exec(); }
Source:
public static IBinding findEnclosingFunction(IASTNode node) { IASTFunctionDefinition functionDefinition = findEnclosingFunctionDefinition(node); if (functionDefinition == null) return null; IASTDeclarator dtor= findInnermostDeclarator(functionDefinition.getDeclarator()); if (dtor != null) { IASTName name= dtor.getName(); if (name != null) { return name.resolveBinding(); } } return null; }

Target:
public static IBinding findEnclosingFunction(IASTNode node) { IASTFunctionDefinition functionDefinition = findAncestorWithType(node, IASTFunctionDefinition.class); if (functionDefinition == null) return null; IASTDeclarator dtor= findInnermostDeclarator(functionDefinition.getDeclarator()); if (dtor != null) { IASTName name= dtor.getName(); if (name != null) { return name.resolveBinding(); } } return null; }
Source:
public void close() throws ConnectException { try { if (writer != null) { writer.close(); writer = null; } if (reader != null) { reader.close(); reader = null; } } catch (IOException e) { throw new ConnectException("Error closing " + logFile, e); } finally { writer = null; reader = null; } }

Target:
public void close() throws ConnectException { try { if (writer != null) { writer.close(); } if (reader != null) { reader.close(); } } catch (IOException e) { throw new DataException("Error closing " + logFile, e); } finally { writer = null; reader = null; } }
Source:
private static void assertRootCause(Exception exception, Class<?> type, String message) { Throwable root = exception; while ( root.getCause() != null ) { root = root.getCause(); } assertTyping( type, root ); assertEquals( root.getMessage(), message ); }

Target:
private static void assertRootCause(Exception exception, Class<?> type, String message) { Throwable root = exception; while ( root.getCause() != null ) { root = root.getCause(); } assertTyping( type, root ); assertEquals( message, root.getMessage() ); }
Source:
private JLabel getSizeMemoryLabel() { if (sizeMemoryLabel == null) { sizeMemoryLabel = new JLabel(); updateMemoryLabel(sizeMemoryLabel, "jvm.options.memory.size", Runtime.getRuntime().totalMemory()); } return sizeMemoryLabel; }

Target:
private ZapLabel getSizeMemoryLabel() { if (sizeMemoryLabel == null) { sizeMemoryLabel = new ZapLabel(); } return sizeMemoryLabel; }
Source:
public SkuDetails(JSONObject source) throws JSONException { String responseType = source.optString(Constants.RESPONSE_TYPE); if (responseType == null) { responseType = Constants.PRODUCT_TYPE_MANAGED; } productId = source.optString(Constants.RESPONSE_PRODUCT_ID); title = source.optString(Constants.RESPONSE_TITLE); description = source.optString(Constants.RESPONSE_DESCRIPTION); isSubscription = responseType.equalsIgnoreCase(Constants.PRODUCT_TYPE_SUBSCRIPTION); currency = source.optString(Constants.RESPONSE_PRICE_CURRENCY); priceLong = source.optLong(Constants.RESPONSE_PRICE_MICROS); priceValue = priceLong / 1000000d; priceText = source.optString(Constants.RESPONSE_PRICE); subscriptionPeriod = source.optString(Constants.RESPONSE_SUBSCRIPTION_PERIOD, "P"); subscriptionFreeTrialPeriod = source.optString(Constants.RESPONSE_FREE_TRIAL_PERIOD, "P"); introductoryPriceLong = source.optLong(Constants.RESPONSE_INTRODUCTORY_PRICE_MICROS); introductoryPriceValue = introductoryPriceLong / 1000000d; introductoryPriceText = source.optString(Constants.RESPONSE_INTRODUCTORY_PRICE); introductoryPricePeriod = source.optString(Constants.RESPONSE_INTRODUCTORY_PRICE_PERIOD, "P"); introductoryPriceCycles = source.optInt(Constants.RESPONSE_INTRODUCTORY_PRICE_CYCLES); }

Target:
public SkuDetails(JSONObject source) throws JSONException { String responseType = source.optString(Constants.RESPONSE_TYPE); if (responseType == null) { responseType = Constants.PRODUCT_TYPE_MANAGED; } productId = source.optString(Constants.RESPONSE_PRODUCT_ID); title = source.optString(Constants.RESPONSE_TITLE); description = source.optString(Constants.RESPONSE_DESCRIPTION); isSubscription = responseType.equalsIgnoreCase(Constants.PRODUCT_TYPE_SUBSCRIPTION); currency = source.optString(Constants.RESPONSE_PRICE_CURRENCY); priceLong = source.optLong(Constants.RESPONSE_PRICE_MICROS); priceValue = priceLong / 1000000d; priceText = source.optString(Constants.RESPONSE_PRICE); subscriptionPeriod = source.optString(Constants.RESPONSE_SUBSCRIPTION_PERIOD); subscriptionFreeTrialPeriod = source.optString(Constants.RESPONSE_FREE_TRIAL_PERIOD); haveTrialPeriod = !TextUtils.isEmpty(subscriptionFreeTrialPeriod); introductoryPriceLong = source.optLong(Constants.RESPONSE_INTRODUCTORY_PRICE_MICROS); introductoryPriceValue = introductoryPriceLong / 1000000d; introductoryPriceText = source.optString(Constants.RESPONSE_INTRODUCTORY_PRICE); introductoryPricePeriod = source.optString(Constants.RESPONSE_INTRODUCTORY_PRICE_PERIOD); haveIntroductoryPeriod = !TextUtils.isEmpty(introductoryPricePeriod); introductoryPriceCycles = source.optInt(Constants.RESPONSE_INTRODUCTORY_PRICE_CYCLES); }
Source:
public DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException { if (isBlank(datasetName)) { throw new IllegalArgumentException("Dataset name cannot be blank"); } if (isBlank(displayName)) { throw new IllegalArgumentException("Display name cannot be blank"); } if (query == null) { throw new IllegalArgumentException("Dataset query is required"); } if (indexBy == null || indexBy.isEmpty()) { throw new IllegalArgumentException("At least one index property is required"); } KeenQueryRequest request = CachedDatasetRequest.creationRequest(datasetName, displayName, query, indexBy); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); }

Target:
public DatasetDefinition create(String datasetName, String displayName, DatasetQuery query, Collection<String> indexBy) throws IOException { Validate.notBlank(datasetName, "Dataset name cannot be blank"); Validate.notBlank(displayName, "Display name cannot be blank"); Validate.notNull(query, "Dataset query is required"); Validate.notEmpty(indexBy, "At least one index property is required"); KeenQueryRequest request = CachedDatasetRequest.creationRequest(datasetName, displayName, query, indexBy); return DatasetDefinition.fromMap(keenQueryClient.getMapResponse(request)); }
Source:
public void getOutput_ReturnsOutput() { Step step = features.get(1).getElements()[0].getSteps()[7]; Output[] outputs = step.getOutput(); ArrayList<String> messages = new ArrayList<>(); for(Output output : outputs) { messages.addAll(Arrays.asList(output.getMessages())); } assertThat(messages.toArray(new String[messages.size()])).containsOnlyOnce( "Could not connect to the server @Rocky@", "Could not connect to the server @Mike@"); }

Target:
public void getOutput_ReturnsOutput() { Step step = features.get(1).getElements()[0].getSteps()[7]; Output[] outputs = step.getOutput(); assertThat(getMessages(outputs)).containsOnlyOnce( "Could not connect to the server @Rocky@", "Could not connect to the server @Mike@"); }
Source:
public void aiMover() { this.players = this.level.getPlayers(); this.units = this.level.getUnits(); for(Unit u:units) { if (u instanceof Enemy) { this.enemies.add((Enemy) u); } } if(players.size() > 0) { this.player = this.players.get(0); movementsX = PathCalculation.calculateXPath((Mover) player, enemies, this.level); movementsY = PathCalculation.calculateYPath((Mover) player, enemies, this.level); for(int i = 0; i < enemies.size(); i++) { Enemy enemy = enemies.get(i); int moveToX = movementsX.get(i); int moveToY = movementsY.get(i); randomizer(enemy); doMoves(enemy, moveToX, moveToY); } } }

Target:
public void aiMover() { this.players = this.level.getPlayers(); this.units = this.level.getUnits(); for(Unit u : units) { if (u instanceof Enemy) { this.enemies.add((Enemy) u); } } if(players.size() > 0) { this.player = this.players.get(0); for(int i = 0; i < enemies.size(); i++) { Enemy enemy = enemies.get(i); int moveToX = PathCalculation.calculateXPath((Mover) player, enemy, this.level); int moveToY = PathCalculation.calculateYPath((Mover) player, enemy, this.level); randomizer(enemy); doMoves(enemy, moveToX, moveToY); } } }
Source:
static public CloseModelDefaultAction getCurrentCloseModelDefaultAction() { String defaultCloseActionString="Prompt"; String saved = TheApp.getCurrentVersionPreferences().get("DefaultCloseAction", defaultCloseActionString); if (saved.equalsIgnoreCase("discard")) currentCloseModelDefaultAction=CloseModelDefaultAction.DISCARD; else if (saved.equalsIgnoreCase("save")) currentCloseModelDefaultAction=CloseModelDefaultAction.SAVE; else currentCloseModelDefaultAction=CloseModelDefaultAction.PROMPT; return currentCloseModelDefaultAction; }

Target:
static public CloseModelDefaultAction getCurrentCloseModelDefaultAction() { String defaultCloseActionString="Prompt"; String saved = TheApp.getCurrentVersionPreferences().get("Internal.DefaultCloseAction", defaultCloseActionString); if (saved.equalsIgnoreCase("discard")) currentCloseModelDefaultAction=CloseModelDefaultAction.DISCARD; else if (saved.equalsIgnoreCase("save")) currentCloseModelDefaultAction=CloseModelDefaultAction.SAVE; else currentCloseModelDefaultAction=CloseModelDefaultAction.PROMPT; return currentCloseModelDefaultAction; }
Source:
int memSize() { return BASE_NODE_SIZE + 2 * 4; }

Target:
int memSize() { return BASE_NODE_SIZE + 3 * 4; }
Source:
private void verifySignatureName(Question question, String questionValue) { Signature signature = SignatureValue.deserialize(questionValue); ViewInteraction name = onView(allOf(withId(R.id.signature_name), withQuestionViewParent(question, SignatureQuestionView.class))) .perform(scrollTo()); name.check(matches(allOf(isDisplayed(), withText(signature.getName())))); }

Target:
private void verifySignatureName(Question question, String questionValue) { Signature signature = SignatureValue.deserialize(questionValue); ViewInteraction name = onView(allOf(withId(R.id.signature_name), withQuestionViewParent(question, SignatureQuestionView.class))) .perform(scrollTo()); name.check(matches(allOf(isDisplayed(), withText(signature.getName()), not(isEnabled())))); }
Source:
private static AddDiskParameters createParameters() { DiskImage image = new DiskImage(); DiskVmElement dve = new DiskVmElement(null, vmId); dve.setDiskInterface(DiskInterface.IDE); dve.setUsingScsiReservation(true); return new AddDiskParameters(dve, image); }

Target:
private static AddDiskParameters createParameters() { DiskImage image = new DiskImage(); DiskVmElement dve = new DiskVmElement(null, vmId); dve.setDiskInterface(DiskInterface.IDE); return new AddDiskParameters(dve, image); }
Source:
public static boolean exists(WebDriver webDriver, By context, By by) { webDriver.manage().timeouts().implicitlyWait(0, TimeUnit.MILLISECONDS); boolean exists = (null == context ? webDriver : webDriver.findElement(context)).findElements(by).size() != 0; webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return exists; }

Target:
public static boolean exists(WebDriver webDriver, By context, By by) { webDriver.manage().timeouts().implicitlyWait(1, TimeUnit.MILLISECONDS); boolean exists = (null == context ? webDriver : webDriver.findElement(context)).findElements(by).size() != 0; webDriver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); return exists; }
Source:
protected void close() throws IOException { synchronized(fdLock) { if (fd != null && fd.valid()) { if (!stream) { ResourceManager.afterUdpClose(); } if (fdUseCount == 0) { if (closePending) { return; } if (!closePending) { SocketTagger.get().untag(fd); } closePending = true; socketClose(); return; } else { if (!closePending) { closePending = true; fdUseCount--; SocketTagger.get().untag(fd); socketPreClose(); } } } } }

Target:
protected void close() throws IOException { synchronized(fdLock) { if (fd != null && fd.valid()) { if (!stream) { ResourceManager.afterUdpClose(); } if (!closePending) { SocketTagger.get().untag(fd); } if (fdUseCount == 0) { if (closePending) { return; } closePending = true; try { socketPreClose(); } finally { socketClose(); } fd = null; return; } else { if (!closePending) { closePending = true; fdUseCount--; socketPreClose(); } } } } }
Source:
private void commitFiles(String commiitMess) { projectExplorer.waitAndSelectItem(PROJECT_NAME); menu.runCommand(TestMenuCommandsConstants.Git.GIT, TestMenuCommandsConstants.Git.COMMIT); git.waitAndRunCommit(commiitMess); git.waitGitStatusBarWithMess(TestGitConstants.COMMIT_MESSAGE_SUCCESS); }

Target:
private void commitFiles(String commiitMess) { projectExplorer.waitAndSelectItem(PROJECT_NAME); menu.runCommand(GIT, COMMIT); git.waitAndRunCommit(commiitMess); git.waitGitStatusBarWithMess(TestGitConstants.COMMIT_MESSAGE_SUCCESS); }
Source:
protected org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense buildNonEmployeeExpense() { org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense nonEmployeeExpense = new org.kuali.kfs.fp.businessobject.DisbursementVoucherNonEmployeeExpense(); return nonEmployeeExpense; }

Target:
protected DisbursementVoucherNonEmployeeExpense buildNonEmployeeExpense() { return new DisbursementVoucherNonEmployeeExpense(); }
Source:
private String wrapSegs(String segmentsLocalStorage) { if (segmentsLocalStorage.equals("")) { return "[]"; } String ksgmnt = "["; String[] segments = segmentsLocalStorage.split(","); if (segments.length > MAX_SEGS_NUMBER_GPT) { segments = Arrays.copyOfRange(segmentsLocalStorage.split(","), 0, MAX_SEGS_NUMBER_GPT); } for (String segment : segments) { ksgmnt += String.format("\"%s\",", segment); } ksgmnt = ksgmnt.substring(0, ksgmnt.length() - 1) + "]"; return ksgmnt; }

Target:
private String wrapSegs(String segmentsLocalStorage) { if ("".equals(segmentsLocalStorage)) { return "[]"; } String ksgmnt = "["; String[] segments = segmentsLocalStorage.split(","); if (segments.length > MAX_SEGS_NUMBER_GPT) { segments = Arrays.copyOfRange(segmentsLocalStorage.split(","), 0, MAX_SEGS_NUMBER_GPT); } for (String segment : segments) { ksgmnt += String.format("\"%s\",", segment); } ksgmnt = ksgmnt.substring(0, ksgmnt.length() - 1) + "]"; return ksgmnt; }