auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void setUp() throws Exception { appContext = InstrumentationRegistry.getTargetContext(); appContext.deleteDatabase("awspinpoint.db"); wifiManager = (WifiManager) InstrumentationRegistry .getContext().getSystemService(Context.WIFI_SERVICE); assertTrue(wifiManager.setWifiEnabled(true)); appId = getPackageConfigure("pinpoint") .getString("AppId"); regions = Regions.fromName(getPackageConfigure("pinpoint") .getString("Region")); credentialsProvider = new CognitoCachingCredentialsProvider( appContext, getPackageConfigure("pinpoint") .getString("identity_pool_id"), regions); <START> pinpointConfiguration = new PinpointConfiguration(appContext, <END> appId, regions, ChannelType.GCM, credentialsProvider); pinpointManager = new PinpointManager(pinpointConfiguration); }</code><technical_language>Indentation off, -4? this is a \t char rendered a double indent (2 x 4 spaces)</technical_language>

Target:
public void setUp() throws Exception { final String identityPoolId = getPackageConfigure("pinpoint") .getString("identity_pool_id"); appId = getPackageConfigure("pinpoint") .getString("AppId"); regions = Regions.fromName(getPackageConfigure("pinpoint") .getString("Region")); appContext = InstrumentationRegistry.getTargetContext(); appContext.deleteDatabase("awspinpoint.db"); wifiManager = (WifiManager) InstrumentationRegistry .getContext().getSystemService(Context.WIFI_SERVICE); assertTrue(wifiManager.setWifiEnabled(true)); credentialsProvider = new CognitoCachingCredentialsProvider( appContext, identityPoolId, regions); pinpointConfiguration = new PinpointConfiguration(appContext, appId, regions, ChannelType.GCM, credentialsProvider); pinpointManager = new PinpointManager(pinpointConfiguration); }
Source:
<code>public void showRateTheAppDialog() { final Resources res = getResources(); AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.rate_app_dialog_title); builder.setMessage(String.format(res.getString(R.string.rate_app_dialog_message), res.getString(R.string.app_name))); builder.setPositiveButton(R.string.label_rate_the_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { <START> AppUpdateUtils.openAppInAppStore(((Dialog) dialog).getContext()); <END> } }); builder.setNegativeButton(R.string.label_maybe_later, null); builder.create().show(); }</code><technical_language>rename AppUpdateUtils</technical_language>

Target:
public void showRateTheAppDialog() { AlertDialog.Builder builder = new AlertDialog.Builder(getContext()); builder.setTitle(R.string.rate_app_dialog_title); builder.setMessage(ResourceUtil.getFormattedString( getResources(), R.string.rate_app_dialog_message, "platform_name", getString(R.string.platform_name))); builder.setPositiveButton(R.string.label_rate_the_app, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { AppStoreUtils.openAppInAppStore(((Dialog) dialog).getContext()); } }); builder.setNegativeButton(R.string.label_maybe_later, null); AlertDialog dialog = builder.create(); dialog.setCanceledOnTouchOutside(false); dialog.show(); }
Source:
<code>private ScheduledFuture<?> startMonitoring() { return monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { int i = getTaskCount(); if (isInterestingEndpoint()) { logger.debug("{} total number of tasks on the executor [{}], connecting [{}], acquiredChannel [{}], availableChannel [{}], pending acquisition [{}]", <START> this.hashCode(), i, connecting.get(), acquiredChannels.size(), availableChannels.size(), pendingAcquisitions.size()); <END> } }, 0, 60, TimeUnit.SECONDS); }</code><technical_language>In runs instrumented include remoteendpoint super useful too</technical_language>

Target:
private ScheduledFuture<?> startMonitoring() { return monitoringRntbdChannelPool.scheduleAtFixedRate(() -> { int i = getTaskCount(); if (isInterestingEndpoint()) { logger.debug("{} total number of tasks on the executor [{}], remote address: [{}], connecting [{}], acquiredChannel [{}], availableChannel [{}], pending acquisition [{}]", this.hashCode(), i, this.remoteAddress(), connecting.get(), acquiredChannels.size(), availableChannels.size(), pendingAcquisitions.size()); } }, 0, 60, TimeUnit.SECONDS); }
Source:
<code>private void performRename(String newName) { RenameSettings settings = dtoFactory.createDto(RenameSettings.class); RenameParams renameParams = dtoFactory.createDto(RenameParams.class); renameParams.setNewName(newName); VirtualFile file = textEditor.getEditorInput().getFile(); TextDocumentIdentifier textDocumentIdentifier = dtoBuildHelper.createTDI(file); renameParams.setTextDocument(textDocumentIdentifier); org.eclipse.lsp4j.Position position = dtoFactory.createDto(org.eclipse.lsp4j.Position.class); position.setCharacter(cursorPosition.getCharacter()); position.setLine(cursorPosition.getLine()); renameParams.setPosition(position); settings.setUpdateReferences(true); settings.setRenameParams(renameParams); settings.setRenameType(RenameType.JAVA_ELEMENT); extensionServiceClient .rename(settings) .then( edits -> { enableAutoSave(); WorkspaceEdit edit = new WorkspaceEdit(); edit.setChanges(edits.getChanges()); edit.setResourceChanges(new LinkedList<>()); for (ResourceChange resourceChange : edits.getResourceChanges()) { edit.getResourceChanges().add(Either.forLeft(resourceChange)); } undoChanges(); applyWorkspaceEditAction.applyWorkspaceEdit(edit); clientServerEventService.sendFileTrackingResumeEvent(); sendOpenEvent(); }) .catchError( error -> { undoChanges(); enableAutoSave(); clientServerEventService.sendFileTrackingResumeEvent(); notificationManager.notify( <START> locale.failedToRename(), error.getMessage(), FAIL, FLOAT_MODE); <END> }); }</code><technical_language>yes, I thinking of</technical_language>

Target:
private void performRename(String newName) { RenameSettings settings = dtoFactory.createDto(RenameSettings.class); RenameParams renameParams = dtoFactory.createDto(RenameParams.class); renameParams.setNewName(newName); VirtualFile file = textEditor.getEditorInput().getFile(); TextDocumentIdentifier textDocumentIdentifier = dtoBuildHelper.createTDI(file); renameParams.setTextDocument(textDocumentIdentifier); org.eclipse.lsp4j.Position position = dtoFactory.createDto(org.eclipse.lsp4j.Position.class); position.setCharacter(cursorPosition.getCharacter()); position.setLine(cursorPosition.getLine()); renameParams.setPosition(position); settings.setUpdateReferences(true); settings.setRenameParams(renameParams); settings.setRenameKind(RenameKind.JAVA_ELEMENT); extensionServiceClient .rename(settings) .then( edits -> { enableAutoSave(); undoChanges(); applyWorkspaceEditAction.applyWorkspaceEdit(edits); clientServerEventService.sendFileTrackingResumeEvent(); sendOpenEvent(); }) .catchError( error -> { undoChanges(); enableAutoSave(); clientServerEventService.sendFileTrackingResumeEvent(); notificationManager.notify( locale.failedToRename(), error.getMessage(), FAIL, FLOAT_MODE); }); }
Source:
<code>public void setClientPolicy(ClientPolicy policy) { this.policy = policy; this.validate(); if (isOpen()) { Future<Void> future = scheduleClose("Policy reset"); try { <START> future.get(2, TimeUnit.SECONDS); <END> } catch (InterruptedException | ExecutionException | TimeoutException e) { log.warn("Policy reset timoued"); } } }</code><technical_language>is reason wait max 2 seconds in this patch set? In previous verified, waiting indefinitely, right</technical_language>

Target:
public void setClientPolicy(ClientPolicy policy) { this.policy = policy; this.validate(); if (!isOpen()) { return; } try (LockWrapper wrapper = new LockWrapper(this.lock)) { if (isOpen() && !this.closing.get()) { scheduleClose("Policy reset"); this.closing.set(true); } } }
Source:
<code>public SubscriptionHelper clear(String path) { Adapter a = subscriptions.remove(path); if (a != null) { requester.unsubscribe(path, null); } <START> return this; <END> }</code><technical_language>Is reason return this methods a side effect? a big fan of personally</technical_language>

Target:
public SubscriptionHelper clear(String path) { subscriptions.remove(path); return this; }
Source:
<code>public void shouldFinishInstallSuccessfully() { waitForCond(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { <START> WebElement element = driver.switchTo().defaultContent().switchTo().frame(1).findElement(By.name("username")); <END> return element != null; } catch (NoSuchElementException | NoSuchFrameException e) { return false; } finally { driver.switchTo().defaultContent(); } } }, 300); }</code><technical_language>IMHO by.name instead of By.name</technical_language>

Target:
public void shouldFinishInstallSuccessfully() { waitForCond(new Callable<Boolean>() { @Override public Boolean call() throws Exception { try { WebElement element = driver.switchTo().defaultContent().switchTo().frame(1).findElement(by.name("username")); return element != null; } catch (NoSuchElementException | NoSuchFrameException e) { return false; } finally { driver.switchTo().defaultContent(); } } }, 300); }
Source:
<code><START> private boolean isSupportedFiletype(File file){ <END> for (String ext : SUPPORTED_FILE_EXTS) { if (file.getName().endsWith(ext)) { return true; } } return false; }</code><technical_language>static</technical_language>

Target:
private static boolean isSupportedFiletype(File file){ for (String ext : SUPPORTED_FILE_EXTS) { if (file.getName().endsWith(ext)) { return true; } } return false; }
Source:
<code>public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception { RequestBuilder requestBuilder = logout(); <START> RequestBuilder defaultRequestBuilder = MockMvcRequestBuilders.get("/"); <END> if (defaultRequestBuilder instanceof ConfigurableSmartRequestBuilder ) { ((ConfigurableSmartRequestBuilder) defaultRequestBuilder).with(new MockPostProcessor()); } if (defaultRequestBuilder != null && requestBuilder instanceof Mergeable ) { requestBuilder = (RequestBuilder) ((Mergeable) requestBuilder).merge(defaultRequestBuilder); } MockHttpServletRequest request = requestBuilder.buildRequest(this.servletContext); Assert.isInstanceOf(ConfigurableSmartRequestBuilder.class, requestBuilder); Assert.isTrue(request.equals(((SmartRequestBuilder) requestBuilder).postProcessRequest(request)), "Postprocessing failed."); }</code><technical_language>If assign this MockHttpServletRequestBuilder need do instanceof casting ConfigurableSmartRequestBuilder Mergeable</technical_language>

Target:
public void postProcessorsAreMergedDuringMockMvcPerform() throws Exception { RequestPostProcessor postProcessor = mock(RequestPostProcessor.class); when(postProcessor.postProcessRequest(any())).thenAnswer(i -> i.getArgument(0)); MockMvc mockMvc = MockMvcBuilders.standaloneSetup(new Object()) .defaultRequest(MockMvcRequestBuilders.get("/").with(postProcessor)) .build(); MvcResult mvcResult = mockMvc.perform(logout()).andReturn(); assertThat(mvcResult.getRequest().getMethod()).isEqualTo(HttpMethod.POST.name()); assertThat(mvcResult.getRequest().getHeader("Accept")) .isEqualTo(MediaType.toString(Arrays.asList(MediaType.TEXT_HTML, MediaType.ALL))); assertThat(mvcResult.getRequest().getRequestURI()).isEqualTo("/logout"); assertThat(mvcResult.getRequest().getParameter("_csrf")).isNotEmpty(); verify(postProcessor).postProcessRequest(any()); }
Source:
<code>public DDF transformScaleMinMax() throws DDFException { <START> return this.transformScaleMinMax(new ArrayList<>(), Boolean.FALSE); <END> }</code><technical_language>wrong false instead of Boolean.FALSE</technical_language>

Target:
public DDF transformScaleMinMax() throws DDFException { return this.transformScaleMinMax(null, Boolean.FALSE); }
Source:
<code>@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this, mViewModelFactory) .get(ReaderPostListViewModel.class); mNewsCardViewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory) .get(NewsCardViewModel.class); <START> mReaderViewModel = ViewModelProviders.of(getParentFragment(), mViewModelFactory) <END> .get(ReaderViewModel.class); if (isFollowingScreen()) { initSubFilterViewModel(); } mViewModel.getShouldCollapseToolbar().observe(this, collapse -> { if (collapse) { mRecyclerView.setToolbarScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); } else { mRecyclerView.setToolbarScrollFlags(0); } }); handleReblogStateChanges(); mViewModel.start(!mIsTopLevel, mReaderViewModel); if (isFollowingScreen()) { mSubFilterViewModel.onUserComesToReader(); } }</code><technical_language>ReaderPostListFragment is screens Reader entry point - eg. Open Reader -> Click a blog title of of posts in discovery tab -> notice ReaderPostListActivity + ReaderPostListFragment created. I getParentFragment return null parent fragment in this scenario. if parent fragment existed ReaderFragment ReaderViewModel exist this create a duplicate of ReaderViewModel used. solution is wrap this mIsTopLevel - a flag indicating in top level (Reader entry point) screen. discuss other solution a call/slack. Wdyt</technical_language>

Target:
@Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); mViewModel = ViewModelProviders.of(this, mViewModelFactory) .get(ReaderPostListViewModel.class); mNewsCardViewModel = ViewModelProviders.of(requireActivity(), mViewModelFactory) .get(NewsCardViewModel.class); if (mIsTopLevel) { mReaderViewModel = ViewModelProviders.of(getParentFragment(), mViewModelFactory) .get(ReaderViewModel.class); } if (isFollowingScreen()) { initSubFilterViewModel(); } mViewModel.getShouldCollapseToolbar().observe(this, collapse -> { if (collapse) { mRecyclerView.setToolbarScrollFlags(AppBarLayout.LayoutParams.SCROLL_FLAG_SCROLL | AppBarLayout.LayoutParams.SCROLL_FLAG_ENTER_ALWAYS); } else { mRecyclerView.setToolbarScrollFlags(0); } }); handleReblogStateChanges(); mViewModel.start(!mIsTopLevel, mReaderViewModel); if (isFollowingScreen()) { mSubFilterViewModel.onUserComesToReader(); } }
Source:
<code>private void processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData(List<PaymentWorksVendor> kfsDisapprovedPmwVendorsToProcess, PaymentWorksNewVendorPayeeAchBatchReportData reportData) { reportData.getDisapprovedVendorsSummary().setRecordCount(kfsDisapprovedPmwVendorsToProcess.size()); for (PaymentWorksVendor pmwVendor : kfsDisapprovedPmwVendorsToProcess) { try { LOG.info("processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData: Vendor was KFS Disapproved. ACH Processing NOT attempted for PMW-vendor-id =" + pmwVendor.getPmwVendorRequestId() + " KFS edoc# = " + pmwVendor.getKfsAchDocumentNumber()); if (allPmwEnteredKfsPayeeAchAccountDataExists(pmwVendor)) { performProcessingWhenAchAccountDataIsProvidedForDisapprovedKfsVendor(pmwVendor, reportData); } else { performProcessingWhenAchAccountDataNotProvidedForDisapprovedKfsVendor(pmwVendor, reportData); } } catch (Exception ex) { <START> LOG.error("processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData: PMW Vendor ID " + pmwVendor.toString() + " generated Exception: " + ex.getStackTrace()); <END> performProcessingWhenExceptionGeneratedForKfsDisapprovedVendorDuringAchCreation(pmwVendor, reportData); } } }</code><technical_language>I getStackTrace() returns array, print expected converted a String. two-arg LOG.error() method pass exception in arg</technical_language>

Target:
private void processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData(List<PaymentWorksVendor> kfsDisapprovedPmwVendorsToProcess, PaymentWorksNewVendorPayeeAchBatchReportData reportData) { reportData.getDisapprovedVendorsSummary().setRecordCount(kfsDisapprovedPmwVendorsToProcess.size()); for (PaymentWorksVendor pmwVendor : kfsDisapprovedPmwVendorsToProcess) { try { LOG.info("processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData: Vendor was KFS Disapproved. ACH Processing NOT attempted for PMW-vendor-id =" + pmwVendor.getPmwVendorRequestId() + " KFS edoc# = " + pmwVendor.getKfsAchDocumentNumber()); if (allPmwEnteredKfsPayeeAchAccountDataExists(pmwVendor)) { performProcessingWhenAchAccountDataIsProvidedForDisapprovedKfsVendor(pmwVendor, reportData); } else { performProcessingWhenAchAccountDataNotProvidedForDisapprovedKfsVendor(pmwVendor, reportData); } } catch (Exception ex) { LOG.error("processEachPaymentWorksDisapprovedNewVendorWithAndWithoutAchData: PMW Vendor ID " + pmwVendor.toString() + " generated Exception(s): ", ex); performProcessingWhenExceptionGeneratedForKfsDisapprovedVendorDuringAchCreation(pmwVendor, reportData); } } }
Source:
<code>private static boolean isSerializable(Tree tree) { if (tree.is(Tree.Kind.ENUM, Tree.Kind.PRIMITIVE_TYPE)) { return true; } else if (tree.is(Tree.Kind.CLASS)) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); return implementsSerializable(symbol.type()); } else if (tree.is(Tree.Kind.EXTENDS_WILDCARD, Tree.Kind.UNBOUNDED_WILDCARD)) { TypeTree bound = ((WildcardTree) tree).bound(); return bound != null && implementsSerializable(bound.symbolType()); <START> } else if (tree.is(Tree.Kind.SUPER_WILDCARD)) { <END> return isSubtypeOfSerializable((WildcardTree) tree); } return implementsSerializable(((TypeTree) tree).symbolType()); }</code><technical_language>merge this conditions other wildcard trees</technical_language>

Target:
private static boolean isSerializable(Tree tree) { if (tree.is(Tree.Kind.ENUM, Tree.Kind.PRIMITIVE_TYPE)) { return true; } else if (tree.is(Tree.Kind.CLASS)) { Symbol.TypeSymbol symbol = ((ClassTree) tree).symbol(); return implementsSerializable(symbol.type()); } else if (tree.is(Tree.Kind.EXTENDS_WILDCARD, Tree.Kind.SUPER_WILDCARD, Tree.Kind.UNBOUNDED_WILDCARD)) { TypeTree bound = ((WildcardTree) tree).bound(); return bound != null && implementsSerializable(bound.symbolType()); } return implementsSerializable(((TypeTree) tree).symbolType()); }
Source:
<code>private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSharedLocks() != null) { for (Entry<String, Guid> entry : lock.getSharedLocks().entrySet()) { if (!insertSharedLock(buildHashMapKey(entry), checkOnly)) { <START> log.debugFormat("Failed to acquire a lock because of shared lock - key :{0} and value {1}", <END> entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire a lock because of exclusive lock - key :{0} and value {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debug("Successed to acquire a lock"); return true; }</code><technical_language>Failed acquire lock. Shared lock is for key :{0} , value: {1}</technical_language>

Target:
private boolean acquireLockInternal(EngineLock lock) { boolean checkOnly = true; for (int i = 0; i < 2; i++) { if (lock.getSharedLocks() != null) { for (Entry<String, Guid> entry : lock.getSharedLocks().entrySet()) { if (!insertSharedLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire lock. Shared lock is taken for key :{0} , value: {1}", entry.getKey(), entry.getValue()); return false; } } } if (lock.getExclusiveLocks() != null) { for (Entry<String, Guid> entry : lock.getExclusiveLocks().entrySet()) { if (!insertExclusiveLock(buildHashMapKey(entry), checkOnly)) { log.debugFormat("Failed to acquire lock. Exclusive lock is taken for key: {0} , value: {1}", entry.getKey(), entry.getValue()); return false; } } } checkOnly = false; } log.debugFormat("Successed acquiring lock {0} succeeded ", lock); return true; }
Source:
<code>public Query createAndStartQuery(final String queryId, final ApplicationInfo applicationInfo, final DAG<ConfigVertex, MISTEdge> configDag) throws ClassNotFoundException, IOException { final Query query = new DefaultQueryImpl(queryId); groupAllocationTableModifier.addEvent(new WritingEvent(WritingEvent.EventType.QUERY_ADD, new Tuple<>(applicationInfo, query))); <START> final Group group = applicationInfo.getRandomGroup(); <END> applicationInfo.getQueryStarter().start(queryId, query, configDag, applicationInfo.getJarFilePath()); return query; }</code><technical_language>please remove this line</technical_language>

Target:
public Query createAndStartQuery(final String queryId, final ApplicationInfo applicationInfo, final DAG<ConfigVertex, MISTEdge> configDag) throws ClassNotFoundException, IOException { final Query query = new DefaultQueryImpl(queryId); groupAllocationTableModifier.addEvent(new WritingEvent(WritingEvent.EventType.QUERY_ADD, new Tuple<>(applicationInfo, query))); applicationInfo.getQueryStarter().start(queryId, query, configDag, applicationInfo.getJarFilePath()); return query; }
Source:
<code>synchronized public void addTab(final ServiceInterface sw) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String name = sw.getName(); String guiClass = String.format("org.myrobotlab.swing.%sGui", sw.getClass().getSimpleName()); log.debug("createTab {}", name, guiClass); ServiceGui newGui = null; newGui = (ServiceGui) Instantiator.getNewInstance(guiClass, name, self); if (newGui == null) { log.info("could not construct a object - creating generic template", guiClass); newGui = (ServiceGui) Instantiator.getNewInstance("org.myrobotlab.swing.NoGui", name, self); } newGui.subscribeGui(); subscribe(name, "publishStatus"); subscribe(name, "publishState"); subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishStatus")), newGui); subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishState")), newGui); send(name, "publishState"); if (getName().equals(name) && guiServiceGui == null) { try { guiServiceGui = (SwingGuiGui) newGui; guiServiceGui.rebuildGraph(); <START> } catch (Exception e) { <END> log.error("Can't cast new guiServiceGui : ", e); } } tabs.addTab(name, newGui.getDisplay(), Runtime.getService(name).getDescription()); tabs.getTabs().setBackgroundAt(tabs.size() - 1, getColorHash(sw.getClass().getSimpleName())); tabs.get(name).transitDockedColor = tabs.getTabs().getBackgroundAt(tabs.size() - 1); } }); }</code><technical_language>do need this try/catch here.. before? change this .. please revert</technical_language>

Target:
synchronized public void addTab(final ServiceInterface sw) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { String name = sw.getName(); String guiClass = String.format("org.myrobotlab.swing.%sGui", sw.getClass().getSimpleName()); log.debug("createTab {}", name, guiClass); ServiceGui newGui = null; newGui = (ServiceGui) Instantiator.getNewInstance(guiClass, name, self); if (newGui == null) { log.info("could not construct a object - creating generic template", guiClass); newGui = (ServiceGui) Instantiator.getNewInstance("org.myrobotlab.swing.NoGui", name, self); } newGui.subscribeGui(); subscribe(name, "publishStatus"); subscribe(name, "publishState"); subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishStatus")), newGui); subscribeToServiceMethod(String.format("%s.%s", name, CodecUtils.getCallBackName("publishState")), newGui); send(name, "publishState"); if (getName().equals(name) && guiServiceGui == null) { guiServiceGui = (SwingGuiGui) newGui; guiServiceGui.rebuildGraph(); } tabs.addTab(name, newGui.getDisplay(), Runtime.getService(name).getDescription()); tabs.getTabs().setBackgroundAt(tabs.size() - 1, getColorHash(sw.getClass().getSimpleName())); tabs.get(name).transitDockedColor = tabs.getTabs().getBackgroundAt(tabs.size() - 1); } }); }
Source:
<code>private void setTimeLatLon(String location) { GridDataset gridDs; try { gridDs = GridDataset.open(location); List grids = gridDs.getGrids(); for (Object grid1 : grids) { GeoGrid grid = (GeoGrid) grid1; if (time == null) { time = grid.getCoordinateSystem().getTimeAxis(); } if (latitude == null) { latitude = grid.getCoordinateSystem().getYHorizAxis(); } if (longitude == null) { longitude = grid.getCoordinateSystem().getXHorizAxis(); } if (time != null && latitude != null && longitude != null) { break; } } <START> gridDs.close(); <END> } catch (IOException e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(e.getMessage()); } if (time == null || latitude == null || longitude == null) { throw new GoGoDuckException(String.format("Unable to retrieve time:%s latitude:%s longitude:%s", time, latitude, longitude)); } }</code><technical_language>in a finally clause try resource block</technical_language>

Target:
private void setTimeLatLon(String location) { GridDataset gridDs = null; try { gridDs = GridDataset.open(location); List grids = gridDs.getGrids(); for (Object grid1 : grids) { GeoGrid grid = (GeoGrid) grid1; if (time == null) { time = grid.getCoordinateSystem().getTimeAxis(); } if (latitude == null) { latitude = grid.getCoordinateSystem().getYHorizAxis(); } if (longitude == null) { longitude = grid.getCoordinateSystem().getXHorizAxis(); } if (time != null && latitude != null && longitude != null) { break; } } } catch (IOException e) { logger.error(e.getMessage(), e); throw new GoGoDuckException(e.getMessage()); } finally { close(gridDs, GridDataset.class); } if (time == null || latitude == null || longitude == null) { throw new GoGoDuckException(String.format("Unable to retrieve time:%s latitude:%s longitude:%s", time, latitude, longitude)); } }
Source:
<code>public void set(String fieldName, Object value) { proxyState.getRealm$realm().checkIfValid(); boolean isString = (value instanceof String); String strValue = isString ? (String) value : null; long columnKey = proxyState.getRow$realm().getColumnKey(fieldName); RealmFieldType type = proxyState.getRow$realm().getColumnType(columnKey); if (isString && type != RealmFieldType.STRING) { switch (type) { case BOOLEAN: value = Boolean.parseBoolean(strValue); break; case INTEGER: value = Long.parseLong(strValue); break; case FLOAT: value = Float.parseFloat(strValue); break; case DOUBLE: value = Double.parseDouble(strValue); break; case DATE: value = JsonUtils.stringToDate(strValue); break; case DECIMAL128: <START> value = new Decimal128(new BigDecimal(strValue)); <END> break; case OBJECT_ID: value = new ObjectId(strValue); break; default: throw new IllegalArgumentException(String.format(Locale.US, "Field %s is not a String field, " + "and the provide value could not be automatically converted: %s. Use a typed" + "setter instead", fieldName, value)); } } if (value == null) { setNull(fieldName); } else { setValue(fieldName, value); } }</code><technical_language>[Decimal123.parse](<LINK_0> instead of BigDecimal</technical_language>

Target:
public void set(String fieldName, Object value) { proxyState.getRealm$realm().checkIfValid(); boolean isString = (value instanceof String); String strValue = isString ? (String) value : null; long columnKey = proxyState.getRow$realm().getColumnKey(fieldName); RealmFieldType type = proxyState.getRow$realm().getColumnType(columnKey); if (isString && type != RealmFieldType.STRING) { switch (type) { case BOOLEAN: value = Boolean.parseBoolean(strValue); break; case INTEGER: value = Long.parseLong(strValue); break; case FLOAT: value = Float.parseFloat(strValue); break; case DOUBLE: value = Double.parseDouble(strValue); break; case DATE: value = JsonUtils.stringToDate(strValue); break; case DECIMAL128: value = Decimal128.parse(strValue); break; case OBJECT_ID: value = new ObjectId(strValue); break; default: throw new IllegalArgumentException(String.format(Locale.US, "Field %s is not a String field, " + "and the provide value could not be automatically converted: %s. Use a typed" + "setter instead", fieldName, value)); } } if (value == null) { setNull(fieldName); } else { setValue(fieldName, value); } }
Source:
<code>public void apply(OfflineCommandContext ctx) throws Exception { <START> if (ctx.version.lessThanOrEqualTo(ServerVersion.VERSION_3_0_0)) { <END> return; } GroovyXmlTransform transform = GroovyXmlTransform.of(ChangeJdbcTransactionAttributes.class) .subtree("transactions", Subtree.subsystem("transactions")) .parameter("useJdbcStore", useJdbcStore != null ? String.valueOf(useJdbcStore) : null) .parameter("storeDatasource", storeDatasource) .parameter("actionStoreDropTable", actionStoreDropTable != null ? String.valueOf(actionStoreDropTable) : null) .parameter("actionStoreTablePrefix", actionStoreTablePrefix) .parameter("communicationStoreDropTable", communicationStoreDropTable != null ? String.valueOf(communicationStoreDropTable) : null) .parameter("communicationStoreTablePrefix", communicationStoreTablePrefix) .parameter("stateStoreDropTable", stateStoreDropTable != null ? String.valueOf(stateStoreDropTable) : null) .parameter("stateStoreTablePrefix", stateStoreTablePrefix) .build(); ctx.client.apply(transform); }</code><technical_language>way, if offline commands version-specific, a good idea add a check this too, offline version discovery works. EDIT: filed #70 for that</technical_language>

Target:
public void apply(OfflineCommandContext ctx) throws Exception { ctx.version.assertAtLeast(ServerVersion.VERSION_2_0_0, "JDBC options are available only for WildFly 8 and higher"); GroovyXmlTransform transform = GroovyXmlTransform.of(ChangeJdbcTransactionAttributes.class) .subtree("transactions", Subtree.subsystem("transactions")) .parameter("useJdbcStore", useJdbcStore != null ? String.valueOf(useJdbcStore) : null) .parameter("storeDatasource", storeDatasource) .parameter("actionStoreDropTable", actionStoreDropTable != null ? String.valueOf(actionStoreDropTable) : null) .parameter("actionStoreTablePrefix", actionStoreTablePrefix) .parameter("communicationStoreDropTable", communicationStoreDropTable != null ? String.valueOf(communicationStoreDropTable) : null) .parameter("communicationStoreTablePrefix", communicationStoreTablePrefix) .parameter("stateStoreDropTable", stateStoreDropTable != null ? String.valueOf(stateStoreDropTable) : null) .parameter("stateStoreTablePrefix", stateStoreTablePrefix) .build(); ctx.client.apply(transform); }
Source:
<code>public void beforeTest() { <START> SWTWorkbenchBot bot = new SWTWorkbenchBot(); <END> SWTBotUtils.createProject(TEST_FOR_FILTERING); SWTBotTreeItem treeItem = SWTBotUtils.selectTracesFolder(bot, TEST_FOR_FILTERING); assertNotNull(treeItem); SWTBotUtils.openTrace(TEST_FOR_FILTERING, FILE_LOCATION.getAbsolutePath(), XMLSTUB_ID); openView(ColorsView.ID); }</code><technical_language>fBot</technical_language>

Target:
public void beforeTest() { SWTBotUtils.createProject(PROJECT_NAME); SWTBotTreeItem treeItem = SWTBotUtils.selectTracesFolder(fBot, PROJECT_NAME); assertNotNull(treeItem); SWTBotUtils.openTrace(PROJECT_NAME, fFileLocation.getAbsolutePath(), XMLSTUB_ID); SWTBotUtils.openView(ColorsView.ID); }
Source:
<code>public void updateEntity() { super.updateEntity(); if (!BuildCraftFactory.quarriesLoadChunks) { isAlive = true; for (int chunkX = box.xMin >> 4; chunkX <= box.xMax >> 4 && isAlive; chunkX++) { for (int chunkZ = box.zMin >> 4; chunkZ <= box.zMax >> 4; chunkZ++) { if (!worldObj.blockExists(chunkX << 4, 64, chunkZ << 4)) { isAlive = false; break; <START> } else System.out.println("chunk exists at "+(chunkX<<4)+","+(chunkZ<<4)); <END> } } if (!isAlive) { if (arm != null) { arm.setDead(); arm = null; } if (builder != null) { builder.setDead(); builder = null; } box.deleteLasers(); } } if (!isAlive && CoreProxy.proxy.isSimulating(worldObj)) { return; } if (!CoreProxy.proxy.isSimulating(worldObj) && isAlive) { return; } if (inProcess) { float energyToUse = 2 + powerProvider.getEnergyStored() / 500; float energy = powerProvider.useEnergy(energyToUse, energyToUse, true); if (energy > 0) { moveHead(0.1 + energy / 200F); } } if (CoreProxy.proxy.isSimulating(worldObj) && inProcess) { sendNetworkUpdate(); } if (inProcess || !isDigging) return; createUtilsIfNeeded(); if (bluePrintBuilder != null) { builderDone = bluePrintBuilder.done; if (!builderDone) { buildFrame(); return; } else { if (builder != null && builder.done()) { box.deleteLasers(); builder.setDead(); builder = null; } } } if (builder == null) { dig(); } }</code><technical_language>this debug print here</technical_language>

Target:
public void updateEntity() { super.updateEntity(); if (!BuildCraftFactory.quarriesLoadChunks) { isAlive = true; for (int chunkX = box.xMin >> 4; chunkX <= box.xMax >> 4 && isAlive; chunkX++) { for (int chunkZ = box.zMin >> 4; chunkZ <= box.zMax >> 4; chunkZ++) { if (!worldObj.blockExists(chunkX << 4, 64, chunkZ << 4)) { isAlive = false; break; } } } if (!isAlive) { if (arm != null) { arm.setDead(); arm = null; } if (builder != null) { builder.setDead(); builder = null; } box.deleteLasers(); } } if (!isAlive && CoreProxy.proxy.isSimulating(worldObj)) { return; } if (!CoreProxy.proxy.isSimulating(worldObj) && isAlive) { return; } if (inProcess) { float energyToUse = 2 + powerProvider.getEnergyStored() / 500; float energy = powerProvider.useEnergy(energyToUse, energyToUse, true); if (energy > 0) { moveHead(0.1 + energy / 200F); } } if (CoreProxy.proxy.isSimulating(worldObj) && inProcess) { sendNetworkUpdate(); } if (inProcess || !isDigging) return; createUtilsIfNeeded(); if (bluePrintBuilder != null) { builderDone = bluePrintBuilder.done; if (!builderDone) { buildFrame(); return; } else { if (builder != null && builder.done()) { box.deleteLasers(); builder.setDead(); builder = null; } } } if (builder == null) { dig(); } }
Source:
<code>public synchronized void unmanage(ManagedBean mBean, String name) { if (mBeanServer != null) { ManagementUtils.register(mBeanServer, mBean, mBean.getType(), name); <START> } <END> mbeans.remove(new Key(mBean, name)); }</code><technical_language>Is this supposed a kind of "lazy registration pattern"? expensive is this operation</technical_language>

Target:
public synchronized void unmanage(ManagedBean mBean, String name) { if (mBeanServer.isPresent()) { ManagementUtils.unregister(mBeanServer.get(), mBean.getType(), name); } mbeans.remove(new Key(mBean, name)); }
Source:
<code>public static String urlToText(URL url, String encoding) throws IOException { if (encoding == null) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { return reader.lines().collect(joining(System.lineSeparator())); } } else { try { try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), Charset.forName(encoding)))) { return reader.lines().collect(joining(System.lineSeparator())); } } catch (UnsupportedCharsetException e) { <START> try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8))) { <END> return reader.lines().collect(joining(System.lineSeparator())); } } } }</code><technical_language>If requested encoding available, do want return string in UTF-8 opposed simply failing method call</technical_language>

Target:
public static String urlToText(URL url, String encoding) throws IOException { Charset charset = encoding == null ? StandardCharsets.UTF_8 : Charset.forName(encoding); try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), charset))) { return reader.lines().collect(joining(System.lineSeparator())); } }
Source:
<code>private static void appendOptionalText(Element element, boolean useTemplateFormat, StringBuilder sb, int indentCount, HashSet<String> unprocessedTags, HashSet<String> skippedTags, boolean includeHtmlTags) throws LicenseXmlException { StringBuilder childSb = new StringBuilder(); if (element.hasChildNodes()) { appendElementChildrenText(element, useTemplateFormat, childSb, indentCount, unprocessedTags, skippedTags, includeHtmlTags); } else { childSb.append(element.getTextContent()); } if (useTemplateFormat) { sb.append("<<beginOptional>>"); if (childSb.length() > 0 && childSb.charAt(0) == ' ') { sb.append(' '); childSb.delete(0, 1); } else if (sb.length() > 0 && !Character.isWhitespace(sb.charAt(sb.length()-1))) { sb.append(' '); } sb.append(childSb); sb.append("<<endOptional>>"); } else if (includeHtmlTags) { if (includesPhrasing(element)) { sb.append("\n<div class=\""); } else { sb.append("\n<var class=\""); } sb.append(HtmlTemplateOutputHandler.OPTIONAL_LICENSE_TEXT_CLASS); sb.append("\">"); sb.append(childSb.toString()); if (includesPhrasing(element)) { <START> sb.append("</div>"); <END> } else { sb.append("</var>"); } } else { if (sb.length() > 0 && !Character.isWhitespace(sb.charAt(sb.length()-1))) { sb.append(' '); } sb.append(childSb); } }</code><technical_language>This a bit DRYer slightly more performant if a single: java if (includesFlowContent(element)) { tag = "div"; } else { tag = "var"; } tag variable for start end tag</technical_language>

Target:
private static void appendOptionalText(Element element, boolean useTemplateFormat, StringBuilder sb, int indentCount, HashSet<String> unprocessedTags, HashSet<String> skippedTags, boolean includeHtmlTags) throws LicenseXmlException { StringBuilder childSb = new StringBuilder(); if (element.hasChildNodes()) { appendElementChildrenText(element, useTemplateFormat, childSb, indentCount, unprocessedTags, skippedTags, includeHtmlTags); } else { childSb.append(element.getTextContent()); } if (useTemplateFormat) { sb.append("<<beginOptional>>"); if (childSb.length() > 0 && childSb.charAt(0) == ' ') { sb.append(' '); childSb.delete(0, 1); } else if (sb.length() > 0 && !Character.isWhitespace(sb.charAt(sb.length()-1))) { sb.append(' '); } sb.append(childSb); sb.append("<<endOptional>>"); } else if (includeHtmlTags) { if (includesFlowControl(element)) { sb.append("\n<div class=\""); } else { sb.append("\n<var class=\""); } sb.append(HtmlTemplateOutputHandler.OPTIONAL_LICENSE_TEXT_CLASS); sb.append("\">"); sb.append(childSb.toString()); if (includesFlowControl(element)) { sb.append("</div>"); } else { sb.append("</var>"); } } else { if (sb.length() > 0 && !Character.isWhitespace(sb.charAt(sb.length()-1))) { sb.append(' '); } sb.append(childSb); } }
Source:
<code>public void onFlushFailure(BatchEntry[] entries) { if (failureListener.isPresent()) { final FailureListener listener = this.failureListener.get(); final Set<Map<String, Serializable>> failedEvents = new HashSet<>(); for (final BatchEntry entry : entries) { final Map<String, Object> eventMap = entry.getEntityEntry().getMap(); <START> final Map<String, Serializable> event = Maps.newHashMapWithExpectedSize(eventMap.size()); <END> eventMap.keySet(). forEach(name -> event.put(name, (Serializable) eventMap.get(name))); failedEvents.add(event); } listener.onFailure(failedEvents); } }</code><technical_language>event a LinkedHashMap eventMap is</technical_language>

Target:
public void onFlushFailure(BatchEntry[] entries) { if (!this.failureListener.isPresent()) { return; } this.failureListener.get().onFailure(entries); }
Source:
<code>public void close() { for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { <START> grouper.close(); <END> } } }</code><technical_language>in case closing grouper throws ex, want close remaining</technical_language>

Target:
public void close() { closed = true; for (Grouper<KeyType> grouper : groupers) { synchronized (grouper) { grouper.close(); } } }
Source:
<code><START> public void adjustedDateSchedule_rollEom_atEom_backwards_noStub() { <END> ZonedDateTime start = ZonedDateTime.of(2012, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC); ZonedDateTime end = ZonedDateTime.of(2013, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC); Period freq = Period.ofMonths(3); RollDateAdjuster eom = EndOfMonthRollDateAdjuster.getAdjuster(); ZonedDateTime[] test = ScheduleCalculator.getAdjustedDateSchedule( start, end, freq, StubType.SHORT_START, MOD_FOL, CALENDAR, eom); assertEquals(4, test.length); assertEquals(ZonedDateTime.of(2012, 7, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[0]); assertEquals(ZonedDateTime.of(2012, 10, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[1]); assertEquals(ZonedDateTime.of(2013, 1, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[2]); assertEquals(ZonedDateTime.of(2013, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC), test[3]); }</code><technical_language>Method name is slightly confusing - includes "noStub" a stub (which is unused). a method called "...noStub" StubType.NONE</technical_language>

Target:
public void adjustedDateSchedule_rollEom_atEom_backwards_noStub() { ZonedDateTime start = ZonedDateTime.of(2012, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC); ZonedDateTime end = ZonedDateTime.of(2013, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC); Period freq = Period.ofMonths(3); RollDateAdjuster eom = EndOfMonthRollDateAdjuster.getAdjuster(); ZonedDateTime[] test = ScheduleCalculator.getAdjustedDateSchedule( start, end, freq, StubType.NONE, MOD_FOL, CALENDAR, eom); assertEquals(4, test.length); assertEquals(ZonedDateTime.of(2012, 7, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[0]); assertEquals(ZonedDateTime.of(2012, 10, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[1]); assertEquals(ZonedDateTime.of(2013, 1, 31, 0, 0, 0, 0, ZoneOffset.UTC), test[2]); assertEquals(ZonedDateTime.of(2013, 4, 30, 0, 0, 0, 0, ZoneOffset.UTC), test[3]); }
Source:
<code><START> public void commitBatch(Region region, List<Mutation> mutations, long blockingMemstoreSize) throws IOException { <END> if (mutations.isEmpty()) { return; } Mutation[] mutationArray = new Mutation[mutations.size()]; for (int i = 0; blockingMemstoreSize > 0 && region.getMemstoreSize() > blockingMemstoreSize && i < 30; i++) { try { checkForRegionClosing(); Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } LOGGER.debug("Committing batch of " + mutations.size() + " mutations for " + region.getRegionInfo().getTable().getNameAsString()); region.batchMutate(mutations.toArray(mutationArray), HConstants.NO_NONCE, HConstants.NO_NONCE); }</code><technical_language>package-private access sufficient for APIs I guess called classes package</technical_language>

Target:
void commitBatch(Region region, List<Mutation> mutations, long blockingMemstoreSize) throws IOException { if (mutations.isEmpty()) { return; } Mutation[] mutationArray = new Mutation[mutations.size()]; for (int i = 0; blockingMemstoreSize > 0 && region.getMemstoreSize() > blockingMemstoreSize && i < 30; i++) { try { checkForRegionClosing(); Thread.sleep(100); } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new IOException(e); } } LOGGER.debug("Committing batch of " + mutations.size() + " mutations for " + region.getRegionInfo().getTable().getNameAsString()); region.batchMutate(mutations.toArray(mutationArray), HConstants.NO_NONCE, HConstants.NO_NONCE); }
Source:
<code>public void variantsSetup(Set<String> enabledFields) throws Exception { String sectionName = "variants"; String[] fieldIds = { "variants", "variants_genesymbol", "variants_interpretation", "variants_inheritance", "variants_validated" }; String[][] headerIds = { { "hgvs_id" }, { "genesymbol", "hgvs_id" }, { "interpretation", "genesymbol", "hgvs_id" }, { "inheritance", "interpretation", "genesymbol", "hgvs_id" }, { "validated", "inheritance", "interpretation", "genesymbol", "hgvs_id" } }; Set<String> present = new HashSet<String>(); int counter = 0; for (String fieldId : fieldIds) { if (enabledFields.remove(fieldId)) { for (String headerId : headerIds[counter]) { present.add(headerId); } } counter++; <START> } <END> this.enabledHeaderIdsBySection.put(sectionName, present); }</code><technical_language>This exact block is repeated 5 times in file -- move a private method</technical_language>

Target:
public void variantsSetup(Set<String> enabledFields) throws Exception { String sectionName = "variants"; String[] fieldIds = { "variants", "variants_genesymbol", "variants_interpretation", "variants_status", "variants_inheritance", "variants_validated" }; String[][] headerIds = { { "hgvs_id" }, { "genesymbol", "hgvs_id" }, { "interpretation", "genesymbol", "hgvs_id" }, { "interpretation", "genesymbol", "hgvs_id" }, { "status", "inheritance", "interpretation", "genesymbol", "hgvs_id" }, { "inheritance", "status", "inheritance", "interpretation", "genesymbol", "hgvs_id" }, { "validated", "inheritance", "status", "interpretation", "genesymbol", "hgvs_id" } }; Set<String> present = addHeaders(fieldIds, headerIds, enabledFields); this.enabledHeaderIdsBySection.put(sectionName, present); }
Source:
<code>public Iterator<Map.Entry<String, String>> iterator() { <START> Map<String, String> map = new HashMap<>(); <END> for (Map.Entry<String, List<String>> entry : this.delegate.getHeaders().entrySet()) { if (!entry.getValue().isEmpty()) { map.put(entry.getKey(), entry.getValue().get(0)); } } return map.entrySet().iterator(); }</code><technical_language>Personally, a wrapping iterator "flat maps" values for a key key,value pairs</technical_language>

Target:
public Iterator<Map.Entry<String, String>> iterator() { final Iterator<Map.Entry<String, List<String>>> iterator = this.delegate.getHeaders() .entrySet().iterator(); return new Iterator<Map.Entry<String, String>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Map.Entry<String, String> next() { Map.Entry<String, List<String>> next = iterator.next(); List<String> value = next.getValue(); return new AbstractMap.SimpleEntry<>(next.getKey(), value.isEmpty() ? "" : value.get(0)); } }; }
Source:
<code>List<Migration> extractMigrations() { Cursor batchesCursor = database.rawQuery(BATCHES_QUERY); List<Migration> migrations = new ArrayList<>(); while (batchesCursor.moveToNext()) { <START> String query = "SELECT uri, _data, total_bytes FROM Downloads WHERE batch_id = ?"; <END> String batchId = batchesCursor.getString(0); String batchTitle = batchesCursor.getString(1); Cursor uriCursor = database.rawQuery(query, batchId); Batch.Builder newBatchBuilder = new Batch.Builder(DownloadBatchIdCreator.createFrom(batchId), batchTitle); List<String> originalFileLocations = new ArrayList<>(); List<FileSize> fileSizes = new ArrayList<>(); while (uriCursor.moveToNext()) { String uri = uriCursor.getString(0); String originalFileName = uriCursor.getString(1); Log.d("MainActivity", batchId + " : " + batchTitle + " : " + uri); newBatchBuilder.addFile(uri); originalFileLocations.add(originalFileName); long rawFileSize = uriCursor.getLong(2); FileSize fileSize = new LiteFileSize(rawFileSize, rawFileSize); fileSizes.add(fileSize); } uriCursor.close(); Batch batch = newBatchBuilder.build(); migrations.add(new Migration(batch, originalFileLocations, fileSizes)); } batchesCursor.close(); return migrations; }</code><technical_language>This a constant</technical_language>

Target:
List<Migration> extractMigrations() { Cursor batchesCursor = database.rawQuery(BATCHES_QUERY); List<Migration> migrations = new ArrayList<>(); while (batchesCursor.moveToNext()) { String batchId = batchesCursor.getString(BATCH_ID_COLUMN); String batchTitle = batchesCursor.getString(TITLE_COLUMN); Cursor uriCursor = database.rawQuery(URIS_QUERY, batchId); Batch.Builder newBatchBuilder = new Batch.Builder(DownloadBatchIdCreator.createFrom(batchId), batchTitle); List<Migration.FileMetadata> fileMetadataList = new ArrayList<>(); while (uriCursor.moveToNext()) { String uri = uriCursor.getString(URI_COLUMN); String originalFileName = uriCursor.getString(FILE_NAME_COLUMN); Log.d("MainActivity", batchId + " : " + batchTitle + " : " + uri); newBatchBuilder.addFile(uri); long rawFileSize = uriCursor.getLong(FILE_SIZE_COLUMN); FileSize fileSize = new LiteFileSize(rawFileSize, rawFileSize); Migration.FileMetadata fileMetadata = new Migration.FileMetadata(originalFileName, fileSize, uri); fileMetadataList.add(fileMetadata); } uriCursor.close(); Batch batch = newBatchBuilder.build(); migrations.add(new Migration(batch, fileMetadataList)); } batchesCursor.close(); return migrations; }
Source:
<code>public static JsonRpcEvent fromMethodAndParams(String method, Map<String, Object> params) throws IOException { return fromByteArray(String.format(MESSAGE_FORMAT, method, <START> MAPPER.writeValueAsString(params)).getBytes()); <END> }</code><technical_language>need encoding. utf-8</technical_language>

Target:
public static JsonRpcEvent fromMethodAndParams(String method, Map<String, Object> params) throws IOException { return fromByteArray(String.format(MESSAGE_FORMAT, method, MAPPER.writeValueAsString(params)) .getBytes(JsonUtils.UTF8)); }