auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewHolder = new ViewHolder(view, isViewingOwnProfile, new Runnable() { @Override public void run() { router.showUserProfileEditor(getActivity(), username); } <START> }); <END> viewHolder.setUsername(username); viewHolder.setAccount(account); }</code><technical_language>Hmm, if ViewHolder a non-static class, access fields (and need passed this click handling Runnable)</technical_language>

Target:
public void onViewCreated(View view, Bundle savedInstanceState) { super.onViewCreated(view, savedInstanceState); viewHolder = new UserProfileViewHolder(view); viewHolder.editProfileButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { router.showUserProfileEditor(getActivity(), username); } }); viewHolder.usernameText.setText(username); setAccount(account); if (null == getAccountTask) { getAccountTask = new GetAccountTask(getActivity(), username) { @Override protected void onSuccess(Account account) throws Exception { setAccount(account); } @Override protected void onException(Exception e) throws RuntimeException { logger.error(e); showErrorMessage(e); } }; getAccountTask.setProgressDialog(viewHolder.loadingIndicator); getAccountTask.execute(); } }
Source:
<code>private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); int columnIndex = 0; for (TmfEventTableColumn column : columns) { ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } <START> if (passedEvent == null || !isVisibleEventColumn(fTable.getColumns()[columnIndex])) { <END> itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } columnIndex++; } return itemStrings.toArray(new String[0]); } }</code><technical_language>ignore margin col</technical_language>

Target:
private String[] getItemStrings(List<TmfEventTableColumn> columns, ITmfEvent event) { if (event == null) { return EMPTY_STRING_ARRAY; } synchronized (columns) { List<String> itemStrings = new ArrayList<>(columns.size()); int columnIndex = 0; for (TmfEventTableColumn column : columns) { ITmfEvent passedEvent = event; if (!(column instanceof TmfMarginColumn) && (event instanceof CachedEvent)) { passedEvent = ((CachedEvent) event).event; } TableColumn viewColumn = fTable.getColumns()[columnIndex]; if (passedEvent == null || (!viewColumn.getResizable() && viewColumn.getWidth() == 0)) { itemStrings.add(EMPTY_STRING); } else { itemStrings.add(column.getItemString(passedEvent)); } columnIndex++; } return itemStrings.toArray(new String[0]); } }
Source:
<code>public void report( SortedMap<String,Gauge> gauges, SortedMap<String,Counter> counters, SortedMap<String,Histogram> histograms, SortedMap<String,Meter> meters, SortedMap<String,Timer> timers ) { String metricKey = gauges.firstKey(); if ( !registeredEvents.containsKey( metricKey ) ) { registry.register( metricKey, (Gauge) () -> registeredEvents.get( metricKey ) ); } <START> <END> registeredEvents.put( metricKey, gauges.get( metricKey ).getValue() ); }</code><technical_language>this strange: registered export of registry in init reporting potentially register some other set of events? is possible</technical_language>

Target:
public void report( SortedMap<String,Gauge> gauges, SortedMap<String,Counter> counters, SortedMap<String,Histogram> histograms, SortedMap<String,Meter> meters, SortedMap<String,Timer> timers ) { String metricKey = gauges.firstKey(); if ( !registeredEvents.containsKey( metricKey ) ) { eventRegistry.register( metricKey, (Gauge) () -> registeredEvents.get( metricKey ) ); } registeredEvents.put( metricKey, gauges.get( metricKey ).getValue() ); }
Source:
<code>@Test public void getSupportedPerformanceDataTypesTest() { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); <START> assert(supportedPerformanceDataTypes.size() == 4); <END> }</code><technical_language>more readable assertEquals instead</technical_language>

Target:
@Test public void getSupportedPerformanceDataTypesTest() { driver.startActivity("io.appium.android.apis", ".ApiDemos"); List<String> dataTypes = new ArrayList<String>(); dataTypes.add("cpuinfo"); dataTypes.add("memoryinfo"); dataTypes.add("batteryinfo"); dataTypes.add("networkinfo"); List<String> supportedPerformanceDataTypes = driver.getSupportedPerformanceDataTypes(); assertEquals(4, supportedPerformanceDataTypes.size()); for ( int i = 0 ; i < supportedPerformanceDataTypes.size() ; ++i) { assertEquals(dataTypes.get(i), supportedPerformanceDataTypes.get(i)); } }
Source:
<code>public void setFlying(boolean value) { if (flying != (flying = value && canFly)) { EventFactory.getInstance().callEvent( <START> new PlayerToggleFlightEvent(this, flying)); <END> } sendAbilities(); }</code><technical_language>This check if event is cancelled. flying field updated event is fired, if event cancelled</technical_language>

Target:
public void setFlying(boolean value) { flying = value && canFly; getServer().sendPlayerAbilities(this); }
Source:
<code>public void sync(ServoControl sc) { this.addServoEventListener(this); <START> subscribe(sc.getName(), "publishServoEvent", getName(), "moveTo"); <END> }</code><technical_language>fancy, test sync here.. o/w end some nasty infinite loops</technical_language>

Target:
public void sync(ServoControl sc) { this.addServoEventListener(this); ((Servo) sc).addServoEventListener((NameProvider) sc); subscribe(sc.getName(), "publishServoEvent", getName(), "moveTo"); }
Source:
<code><START> public void saveSentMessage_shouldReturnTheSavedMessage() { <END> Message m = new Message(); m.setId(17); m.setSubject("for test"); m.setContent("content for testing"); User sender = new User(); sender.setId(27); SentMessage sm = sentMessageService.saveSentMessage(new SentMessage(m, sender.getUserId(), null)); Assert.assertNotNull(sm); Assert.assertEquals(m.getId(), sm.getMessageId()); Assert.assertEquals(sender.getUserId(), sm.getSenderId()); }</code><technical_language>![Codacy](<LINK_0> Issue found: [Method names underscores](<LINK_1></technical_language>

Target:
public void saveSentMessage_shouldReturnTheSavedMessage() { Message m = new Message(); m.setId(17); m.setSubject("for test"); m.setContent("content for testing"); User sender = new User(); sender.setId(27); SentMessage sm = sentMessageService.saveSentMessage(new SentMessage(m, sender, null)); Assert.assertNotNull(sm); Assert.assertEquals(m.getId(), sm.getMessageId()); Assert.assertEquals(sender.getUserId(), sm.getSender().getUserId()); }
Source:
<code>boolean exists(K key, String name) { if (key == null) { return false; } <START> List<V> list = getDataMap().get(key); <END> if (list == null) { return false; } for (V data : list) { if (getDataName(data).equals(name)) { return true; } } return false; }</code><technical_language>find</technical_language>

Target:
boolean exists(K key, String name) { return find(key, name) != null; }
Source:
<code>private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) <START> .setSoTimeout(socketTimeout > 0 ? socketTimeout : TIMEOUT_THREE_HOURS) <END> .build(); }</code><technical_language>Okay, I misread that. I a parameter now. In case, throwing exception invalid timeout more reasonable silently ignoring a substituted default value</technical_language>

Target:
private SocketConfig createSocketConfig(int socketTimeout) { return SocketConfig.custom() .setSoReuseAddress(true) .setSoTimeout(socketTimeout) .build(); }
Source:
<code>private int daysWithoutPasswordChange(MotechUser user) { <START> return Days.daysBetween(user.getLastPasswordChange(), DateTime.now()).getDays(); <END> }</code><technical_language>DateUtil.now()</technical_language>

Target:
private int daysWithoutPasswordChange(MotechUser user) { return Days.daysBetween(user.getLastPasswordChange(), DateUtil.now()).getDays(); }
Source:
<code>public synchronized void report(int seqnum, long time) { cache.put(seqnum, time); <START> assert(cache.size() <= cache.maxSize); <END> }</code><technical_language>this assert here. Do want asserts in code</technical_language>

Target:
public synchronized void report(int seqnum, long time) { cache.put(seqnum, time); }
Source:
<code>public void run() { long delayMS = pollPeriodinMS; try { final long pollStartTime = System.nanoTime(); poll(); final long pollEndTime = System.nanoTime(); final long pollTimeNS = pollEndTime - pollStartTime; final long pollTimeMS = TimeUnit.NANOSECONDS.toMillis(pollTimeNS); delayMS = Math.max(pollPeriodinMS - pollTimeMS, 0); } catch (Exception e) { log.makeAlert(e, "Problem polling Coordinator.").emit(); } <START> scheduledExec.schedule(new PollTask(), delayMS, TimeUnit.MILLISECONDS); <END> }</code><technical_language>I catch InterruptedException schedule more tasks it</technical_language>

Target:
public void run() { long delayMS = pollPeriodInMS; try { final long pollStartTime = System.nanoTime(); poll(); final long pollEndTime = System.nanoTime(); final long pollTimeNS = pollEndTime - pollStartTime; final long pollTimeMS = TimeUnit.NANOSECONDS.toMillis(pollTimeNS); delayMS = Math.max(pollPeriodInMS - pollTimeMS, 0); } catch (Exception e) { log.makeAlert(e, "Problem polling Coordinator.").emit(); } finally { if (!Thread.currentThread().isInterrupted()) { scheduledExec.schedule(new PollTask(), delayMS, TimeUnit.MILLISECONDS); } } }
Source:
<code>public Integer getNumberOfPrograms() { <START> return numberOfPrograms; <END> }</code><technical_language>this field retrieved results.size() stored in private field</technical_language>

Target:
public int getNumberOfPrograms() { return results.size(); }
Source:
<code>private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { <START> LogUtil.w(be, "Binding error, sleep 1 second ..."); <END> if (firstException == null) { firstException = be; } sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }</code><technical_language>prefer constant TIME_BETWEEN_RETRIES_MS</technical_language>

Target:
private static LocalServerSocket bindToSocket(String address) throws IOException { int retries = MAX_BIND_RETRIES; IOException firstException = null; do { try { if (LogUtil.isLoggable(Log.DEBUG)) { LogUtil.d("Trying to bind to @" + address); } return new LocalServerSocket(address); } catch (BindException be) { LogUtil.w(be, "Binding error, sleep " + TIME_BETWEEN_BIND_RETRIES_MS + " ms..."); if (firstException == null) { firstException = be; } Util.sleepUninterruptibly(TIME_BETWEEN_BIND_RETRIES_MS); } } while (retries-- > 0); throw firstException; }
Source:
<code>public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); Patient patientToAddThenRemove = new Patient(4); <START> assertFalse(service.getCohort(2).contains(patientToAddThenRemove.getPatientId())); <END> try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }</code><technical_language>I imagine a new contains method takes in patient object internally delegates need changes</technical_language>

Target:
public void removePatientFromCohort_shouldNotFailIfCohortDoesNotContainPatient() throws Exception { executeDataSet(COHORT_XML); Patient patientToAddThenRemove = new Patient(4); assertFalse(service.getCohort(2).contains(patientToAddThenRemove)); try { service.removePatientFromCohort(service.getCohort(2), patientToAddThenRemove); } catch (Exception e) { Assert.fail("removePatientFromCohort(Cohort,Patient) should not fail if cohort doesn't contain patient"); } }
Source:
<code>private void writeStatistics(final Region region, boolean delete, List<Mutation> mutations, long currentTime, Scan scan) throws IOException { Set<ImmutableBytesPtr> fams = guidePostsInfoWriterMap.keySet(); if (cachedGuidePosts == null) { boolean collectingForLocalIndex = scan != null && !scan.getFamilyMap().isEmpty() && MetaDataUtil.isLocalIndexFamily(scan.getFamilyMap().keySet().iterator().next()); for (Store store : region.getStores()) { ImmutableBytesPtr cfKey = new ImmutableBytesPtr(store.getFamily().getName()); boolean isLocalIndexStore = MetaDataUtil.isLocalIndexFamily(cfKey); if (isLocalIndexStore != collectingForLocalIndex) { continue; } if (!guidePostsInfoWriterMap.containsKey(cfKey)) { Pair<Long, GuidePostsInfoBuilder> emptyGps = new Pair<Long, GuidePostsInfoBuilder>(0l, new GuidePostsInfoBuilder()); guidePostsInfoWriterMap.put(cfKey, emptyGps); } } } for (ImmutableBytesPtr fam : fams) { <START> if (delete) { <END> statsWriter.deleteStatsForRegion(region, this, fam, mutations); LOG.info("Generated " + mutations.size() + " mutations to delete existing stats"); } if (this.guidePostDepth > 0) { int oldSize = mutations.size(); statsWriter.addStats(this, fam, mutations); LOG.info("Generated " + (mutations.size() - oldSize) + " mutations for new stats"); } } }</code><technical_language>line 228 line 237, removed conditional debug logs add info log, this is necessary</technical_language>

Target:
private void writeStatistics(final Region region, boolean delete, List<Mutation> mutations, long currentTime, Scan scan) throws IOException { Set<ImmutableBytesPtr> fams = guidePostsInfoWriterMap.keySet(); if (cachedGuidePosts == null) { boolean collectingForLocalIndex = scan != null && !scan.getFamilyMap().isEmpty() && MetaDataUtil.isLocalIndexFamily(scan.getFamilyMap().keySet().iterator().next()); for (Store store : region.getStores()) { ImmutableBytesPtr cfKey = new ImmutableBytesPtr(store.getFamily().getName()); boolean isLocalIndexStore = MetaDataUtil.isLocalIndexFamily(cfKey); if (isLocalIndexStore != collectingForLocalIndex) { continue; } if (!guidePostsInfoWriterMap.containsKey(cfKey)) { Pair<Long, GuidePostsInfoBuilder> emptyGps = new Pair<Long, GuidePostsInfoBuilder>(0l, new GuidePostsInfoBuilder()); guidePostsInfoWriterMap.put(cfKey, emptyGps); } } } for (ImmutableBytesPtr fam : fams) { if (delete) { statsWriter.deleteStatsForRegion(region, this, fam, mutations); LOG.info("Generated " + mutations.size() + " mutations to delete existing stats"); } if (this.guidePostDepth > 0) { int oldSize = mutations.size(); statsWriter.addStats(this, fam, mutations, guidePostDepth); LOG.info("Generated " + (mutations.size() - oldSize) + " mutations for new stats"); } } }
Source:
<code>public long acceptWay(ReaderWay way) { String highwayValue = way.getTag("highway"); if (highwayValue == null) { long acceptPotentially = 0; if (way.hasTag("route", ferries)) { String footTag = way.getTag("foot"); if (footTag == null || "yes".equals(footTag)) <START> acceptPotentially = acceptBit | ferryBit; <END> } if (way.hasTag("railway", "platform")) acceptPotentially = acceptBit; if (way.hasTag("man_made", "pier")) acceptPotentially = acceptBit; if (acceptPotentially != 0) { if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; return acceptBit; } return 0; } String sacScale = way.getTag("sac_scale"); if (sacScale != null) { if (!"hiking".equals(sacScale) && !"mountain_hiking".equals(sacScale) && !"demanding_mountain_hiking".equals(sacScale) && !"alpine_hiking".equals(sacScale)) return 0; } if (way.hasTag("foot", intendedValues)) return acceptBit; if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; if (way.hasTag("sidewalk", sidewalkValues)) return acceptBit; if (!allowedHighwayTags.contains(highwayValue)) return 0; if (way.hasTag("motorroad", "yes")) return 0; if (isBlockFords() && (way.hasTag("highway", "ford") || way.hasTag("ford"))) return 0; if (getConditionalTagInspector().isPermittedWayConditionallyRestricted(way)) return 0; return acceptBit; }</code><technical_language>right do "return acceptBit" end</technical_language>

Target:
public long acceptWay(ReaderWay way) { String highwayValue = way.getTag("highway"); if (highwayValue == null) { long acceptPotentially = 0; if (way.hasTag("route", ferries)) { String footTag = way.getTag("foot"); if (footTag == null || "yes".equals(footTag)) acceptPotentially = acceptBit | ferryBit; } if (way.hasTag("railway", "platform")) acceptPotentially = acceptBit; if (way.hasTag("man_made", "pier")) acceptPotentially = acceptBit; if (acceptPotentially != 0) { if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; return acceptPotentially; } return 0; } String sacScale = way.getTag("sac_scale"); if (sacScale != null) { if (!"hiking".equals(sacScale) && !"mountain_hiking".equals(sacScale) && !"demanding_mountain_hiking".equals(sacScale) && !"alpine_hiking".equals(sacScale)) return 0; } if (way.hasTag("foot", intendedValues)) return acceptBit; if (way.hasTag(restrictions, restrictedValues) && !getConditionalTagInspector().isRestrictedWayConditionallyPermitted(way)) return 0; if (way.hasTag("sidewalk", sidewalkValues)) return acceptBit; if (!allowedHighwayTags.contains(highwayValue)) return 0; if (way.hasTag("motorroad", "yes")) return 0; if (isBlockFords() && (way.hasTag("highway", "ford") || way.hasTag("ford"))) return 0; if (getConditionalTagInspector().isPermittedWayConditionallyRestricted(way)) return 0; return acceptBit; }
Source:
<code>public String putIfAbsent(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); String result = value; Query query = new Query(Criteria.where("key").is(key)); if (template.exists(query, collectionName)) { result = null; } else { template.save(new Datastore(key, value), collectionName); } <START> return result; <END> }</code><technical_language>insert exists for operation</technical_language>

Target:
public String putIfAbsent(String key, String value) { Assert.notNull(key, "'key' must not be null."); Assert.notNull(value, "'value' must not be null."); BasicDBObject result = (BasicDBObject) operations.call(PUT_IF_ABSENT, key, value); return (result == null) ? null : (String) result.get(VALUE); }
Source:
<code>final static <T> int getFirstKeyframeIndexAtTime (final Array<NodeKeyframe<T>> arr, final float time) { final int lastIndex = arr.size - 1; if (lastIndex < 0 || time < arr.get(0).keytime || time > arr.get(lastIndex).keytime) { return 0; } int minIndex = 0; int maxIndex = lastIndex; <START> for (;;) { <END> final float minTime = arr.get(minIndex).keytime; final float maxTime = arr.get(maxIndex).keytime; if (time < minTime) { return Math.max(0, minIndex - 1); } if (time > maxTime) { return Math.min(lastIndex - 1, maxIndex); } if (minTime == maxTime) { return minIndex; } float t = (time - minTime) / (maxTime - minTime); int index = (int)(minIndex + t * (maxIndex - minIndex)); if (time < arr.get(index).keytime) { maxIndex = index - 1; } else if (time > arr.get(index).keytime) { minIndex = index + 1; } else { return Math.min(lastIndex - 1, index); } } }</code><technical_language>while(true)</technical_language>

Target:
final static <T> int getFirstKeyframeIndexAtTime (final Array<NodeKeyframe<T>> arr, final float time) { final int lastIndex = arr.size - 1; if (lastIndex <= 0 || time < arr.get(0).keytime || time > arr.get(lastIndex).keytime) { return 0; } int minIndex = 0; int maxIndex = lastIndex; while (minIndex < maxIndex) { int i = (minIndex + maxIndex) / 2; if (time > arr.get(i + 1).keytime) { minIndex = i + 1; } else if (time < arr.get(i).keytime) { maxIndex = i - 1; } else { return i; } } return minIndex; }
Source:
<code>private void doAppLogAggregationPostCleanUp() { List<Path> localAppLogDirs = new ArrayList<Path>(); for (String rootLogDir : dirsHandler.getLogDirsForCleanup()) { Path logPath = new Path(rootLogDir, applicationId); try { lfs.getFileStatus(logPath); localAppLogDirs.add(logPath); } catch (UnsupportedFileSystemException ue) { <START> LOG.warn("Log dir " + rootLogDir + <END> " is in an unsupported file system", ue); continue; } catch (IOException fe) { LOG.warn("An exception occurred while getting file information", fe); continue; } } if (localAppLogDirs.size() > 0) { LOG.debug("Cleaning up files", localAppLogDirs.size()); List<Path> localAppLogDirsList = new ArrayList<>(); localAppLogDirsList.addAll(localAppLogDirs); DeletionTask deletionTask = new FileDeletionTask(delService, this.userUgi.getShortUserName(), null, localAppLogDirsList); this.delService.delete(deletionTask); } }</code><technical_language>{} placeholders</technical_language>

Target:
private void doAppLogAggregationPostCleanUp() { List<Path> localAppLogDirs = new ArrayList<Path>(); for (String rootLogDir : dirsHandler.getLogDirsForCleanup()) { Path logPath = new Path(rootLogDir, applicationId); try { lfs.getFileStatus(logPath); localAppLogDirs.add(logPath); } catch (UnsupportedFileSystemException ue) { LOG.warn("Log dir is in an unsupported file system", rootLogDir, ue); continue; } catch (IOException fe) { LOG.warn("An exception occurred while getting file information", fe); continue; } } if (localAppLogDirs.size() > 0) { LOG.debug("Cleaning up files", localAppLogDirs.size()); List<Path> localAppLogDirsList = new ArrayList<>(); localAppLogDirsList.addAll(localAppLogDirs); DeletionTask deletionTask = new FileDeletionTask(delService, this.userUgi.getShortUserName(), null, localAppLogDirsList); this.delService.delete(deletionTask); } }
Source:
<code>public static QueryOriginContext create(HttpServletRequest httpServletRequest, String query) { String userAgent = httpServletRequest.getHeader("User-Agent"); <START> String clientId = httpServletRequest.getHeader("X-Alient-Client-Id"); <END> return QueryOriginContext.of(httpServletRequest.getRemoteAddr(), httpServletRequest.getRemoteHost(), httpServletRequest.getRemotePort(), userAgent == null ? "" : userAgent, clientId == null ? "" : clientId, query); }</code><technical_language>change header name "X-Client-Id" instead</technical_language>

Target:
public static QueryOriginContext create(HttpServletRequest httpServletRequest, String query) { String userAgent = httpServletRequest.getHeader("User-Agent"); String clientId = httpServletRequest.getHeader("X-Client-Id"); return QueryOriginContext.of(httpServletRequest.getRemoteAddr(), httpServletRequest.getRemoteHost(), httpServletRequest.getRemotePort(), userAgent == null ? "" : userAgent, clientId == null ? "" : clientId, query); }
Source:
<code>public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); if (dataBytes == null || dataBytes.length == 0) { return null; } <START> return new String(dataBytes, charset); <END> } catch (NodeExistsException e) { } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }</code><technical_language>rewritten return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset);</technical_language>

Target:
public String doGetContent(String path) { try { byte[] dataBytes = client.getData().forPath(path); return (dataBytes == null || dataBytes.length == 0) ? null : new String(dataBytes, charset); } catch (NoNodeException e) { } catch (Exception e) { throw new IllegalStateException(e.getMessage(), e); } return null; }
Source:
<code>public void run() { Shell parent = <START> Display.getDefault().getActiveShell(); <END> FileDialog fileDialog = new FileDialog(parent, SWT.SAVE); String filePath = fileDialog.open(); if (filePath != null) { File file = new File(filePath); if (file.exists()) { MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \"" + file.toString() + "\" already exists. Do you want to replace the existing one?", MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[DIALOG_BUTTON_LABELS .size()]), 1); int open = messageDialog.open(); if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) { saveComparison(file); refreshLocation(filePath); } } else { saveComparison(file); refreshLocation(filePath); } } super.run(); }</code><technical_language>Display.getDefault() if obtain PlatformUI.getWorkbench()</technical_language>

Target:
public void run() { Shell parent = getShell(); FileDialog fileDialog = new FileDialog(parent, SWT.SAVE); String filePath = fileDialog.open(); if (filePath != null) { File file = new File(filePath); if (file.exists()) { MessageDialog messageDialog = new MessageDialog(parent, "File already exists", null, "File \"" + file.toString() + "\" already exists. Do you want to replace the existing one?", MessageDialog.WARNING, DIALOG_BUTTON_LABELS.toArray(new String[DIALOG_BUTTON_LABELS .size()]), 1); int open = messageDialog.open(); if (open == DIALOG_BUTTON_LABELS.indexOf("Replace")) { saveComparison(file); refreshLocation(filePath); } } else { saveComparison(file); refreshLocation(filePath); } } super.run(); }
Source:
<code>public void testAddHostedEngineStorageFails() { when(command.getLUNsFromVgInfo(parameters.getStorageDomain().getStorage())).thenReturn(getLUNs()); doReturn(new ArrayList<LUNs>()).when(command).getAllLuns(); parameters.getStorageDomain().setStorageName(StorageConstants.HOSTED_ENGINE_STORAGE_DOMAIN_NAME); assertFalse(command.canAddDomain()); <START> CanDoActionTestUtils.assertCanDoActionMessages("", command, VdcBllMessages.ACTION_TYPE_FAILED_HOSTED_ENGINE_STORAGE); <END> }</code><technical_language>Please add a message instead of empty string</technical_language>

Target:
public void testAddHostedEngineStorageFails() { when(command.getLUNsFromVgInfo(parameters.getStorageDomain().getStorage())).thenReturn(getLUNs()); doReturn(new ArrayList<LUNs>()).when(command).getAllLuns(); parameters.getStorageDomain().setStorageName(StorageConstants.HOSTED_ENGINE_STORAGE_DOMAIN_NAME); assertFalse(command.canAddDomain()); CanDoActionTestUtils.assertCanDoActionMessages("Add self hosted engine storage domain succeeded where it should have failed", command, VdcBllMessages.ACTION_TYPE_FAILED_HOSTED_ENGINE_STORAGE); }
Source:
<code>public void retrievesForks() throws Exception { final RtForks forks = new RtForks(new FakeRequest(), this.repo()); MatcherAssert.assertThat( forks.iterate("newest"), <START> Matchers.notNullValue() <END> ); }</code><technical_language>test checks nothing, iterate() method return nonNull object. worth forks.iterate("newest").next() check for some attribute</technical_language>

Target:
public void retrievesForks() throws Exception { }
Source:
<code>public CalibrationSet getMostRecentCalibrations(DataSource dataSource, long instrumentId, LocalDateTime date) throws CalibrationException, DatabaseException, MissingParamException, RecordNotFoundException { CalibrationSet result = new CalibrationSet(instrumentId, getCalibrationType(), getTargets(dataSource, instrumentId)); Connection conn = null; PreparedStatement stmt = null; ResultSet records = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(GET_RECENT_CALIBRATIONS_QUERY); stmt.setLong(1, instrumentId); stmt.setString(2, getCalibrationType()); <START> stmt.setLong(3, date.toEpochSecond(ZoneOffset.UTC) * 1000); <END> records = stmt.executeQuery(); while (!result.isComplete() && records.next()) { String target = records.getString(1); if (!result.containsTarget(target)) { LocalDateTime deploymentDate = DateTimeUtils.longToDate(records.getLong(2)); List<Double> coefficients = StringUtils.delimitedToDoubleList(records.getString(3)); String calibrationClass = records.getString(4); Calibration calibration = CalibrationFactory.createCalibration(getCalibrationType(), calibrationClass, instrumentId, deploymentDate, target, coefficients); result.add(calibration); } } } catch (SQLException e) { throw new DatabaseException("Error while retrieving calibrations", e); } finally { DatabaseUtils.closeResultSets(records); DatabaseUtils.closeStatements(stmt); DatabaseUtils.closeConnection(conn); } return result; }</code><technical_language>DateTimeUtils.dateToLong</technical_language>

Target:
public CalibrationSet getMostRecentCalibrations(DataSource dataSource, long instrumentId, LocalDateTime date) throws CalibrationException, DatabaseException, MissingParamException, RecordNotFoundException { CalibrationSet result = new CalibrationSet(instrumentId, getCalibrationType(), getTargets(dataSource, instrumentId)); Connection conn = null; PreparedStatement stmt = null; ResultSet records = null; try { conn = dataSource.getConnection(); stmt = conn.prepareStatement(GET_RECENT_CALIBRATIONS_QUERY); stmt.setLong(1, instrumentId); stmt.setString(2, getCalibrationType()); stmt.setLong(3, DateTimeUtils.dateToLong(date)); records = stmt.executeQuery(); while (!result.isComplete() && records.next()) { String target = records.getString(1); if (!result.containsTarget(target)) { LocalDateTime deploymentDate = DateTimeUtils.longToDate(records.getLong(2)); List<Double> coefficients = StringUtils.delimitedToDoubleList(records.getString(3)); String calibrationClass = records.getString(4); Calibration calibration = CalibrationFactory.createCalibration(getCalibrationType(), calibrationClass, instrumentId, deploymentDate, target, coefficients); result.add(calibration); } } } catch (SQLException e) { throw new DatabaseException("Error while retrieving calibrations", e); } finally { DatabaseUtils.closeResultSets(records); DatabaseUtils.closeStatements(stmt); DatabaseUtils.closeConnection(conn); } return result; }
Source:
<code><START> public boolean equals(Object o) { <END> if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ApplyStaticNatVspCommand that = (ApplyStaticNatVspCommand) o; if (_isL3Network != that._isL3Network) return false; if (_isVpc != that._isVpc) return false; if (_networkDomainUuid != null ? !_networkDomainUuid.equals(that._networkDomainUuid) : that._networkDomainUuid != null) return false; if (_networkUuid != null ? !_networkUuid.equals(that._networkUuid) : that._networkUuid != null) return false; if (_staticNatDetails != null ? !_staticNatDetails.equals(that._staticNatDetails) : that._staticNatDetails != null) return false; if (_vpcOrSubnetUuid != null ? !_vpcOrSubnetUuid.equals(that._vpcOrSubnetUuid) : that._vpcOrSubnetUuid != null) return false; return true; }</code><technical_language>This equals implementation include attributes Command super class</technical_language>

Target:
public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ApplyStaticNatVspCommand)) return false; if (!super.equals(o)) return false; ApplyStaticNatVspCommand that = (ApplyStaticNatVspCommand) o; if (_isL3Network != that._isL3Network) return false; if (_isVpc != that._isVpc) return false; if (_networkDomainUuid != null ? !_networkDomainUuid.equals(that._networkDomainUuid) : that._networkDomainUuid != null) return false; if (_networkUuid != null ? !_networkUuid.equals(that._networkUuid) : that._networkUuid != null) return false; if (_staticNatDetails != null ? !_staticNatDetails.equals(that._staticNatDetails) : that._staticNatDetails != null) return false; if (_vpcOrSubnetUuid != null ? !_vpcOrSubnetUuid.equals(that._vpcOrSubnetUuid) : that._vpcOrSubnetUuid != null) return false; return true; }
Source:
<code><START> private boolean nullOrEmpty(List<?> list) { <END> return list == null || list.isEmpty(); }</code><technical_language>static</technical_language>

Target:
private static boolean nullOrEmpty(List<?> list) { return list == null || list.isEmpty(); }
Source:
<code>protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (finishIfNotRoot()) { return; } if (savedInstanceState != null) { shortcutExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); } <START> shouldCheckForLocalAppFilesChange = CommCareApplication._().isConsumerApp(); <END> }</code><technical_language>matter if rotate screen? this trigger update checks more wanted</technical_language>

Target:
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (finishIfNotRoot()) { return; } if (savedInstanceState != null) { shortcutExtraWasConsumed = savedInstanceState.getBoolean(EXTRA_CONSUMED_KEY); alreadyCheckedForAppFilesChange = savedInstanceState.getBoolean(KEY_APP_FILES_CHECK_OCCURRED); } }
Source:
<code>public void shouldReturnSome() { Option<String> oneToOne = HashMap.of(1, "One").lift().apply(1); <START> assertThat(oneToOne instanceof Option.Some); <END> }</code><technical_language>I this test is green, assertion _check_ called. check concrete value, i.e. java assertThat(oneToOne).isEqualTo(Option.some("One"));</technical_language>

Target:
public void shouldReturnSome() { Option<String> oneToOne = HashMap.of(1, "One").lift().apply(1); assertThat(oneToOne).isEqualTo(Option.some("One")); }
Source:
<code>private void handle(final APIChangeInstanceOfferingMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIChangeInstanceOfferingEvent evt = new APIChangeInstanceOfferingEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { <START> bus.replyErrorByMessageType(msg, allowed); <END> return; } changeOffering(msg, new Completion(msg, chain) { @Override public void success() { refreshVO(); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "change-instance-offering"; } }); }</code><technical_language>fix</technical_language>

Target:
private void handle(final APIChangeInstanceOfferingMsg msg) { thdf.chainSubmit(new ChainTask(msg) { @Override public String getSyncSignature() { return syncThreadName; } @Override public void run(SyncTaskChain chain) { APIChangeInstanceOfferingEvent evt = new APIChangeInstanceOfferingEvent(msg.getId()); refreshVO(); ErrorCode allowed = validateOperationByState(msg, self.getState(), SysErrors.OPERATION_ERROR); if (allowed != null) { throw new OperationFailureException(operr("operation is not allowed to vm[uuid:%s] which is in the state of state:%s", self.getUuid(), self.getState())); } changeOffering(msg, new Completion(msg, chain) { @Override public void success() { refreshVO(); evt.setInventory(getSelfInventory()); bus.publish(evt); chain.next(); } @Override public void fail(ErrorCode errorCode) { evt.setError(errorCode); bus.publish(evt); chain.next(); } }); } @Override public String getName() { return "change-instance-offering"; } }); }
Source:
<code>public boolean set(PermanentProperty prop, Object value, Flag flag) { synchronized (coreLock) { boolean result = false; if (prop == Value.POSITION && value instanceof String) { team.field(this, team.getPosition(FloorPosition.fromString((String)value))); } else if (prop == Value.ROLE && value instanceof String) { team.field(this, Role.fromString((String)value)); } else { requestBatchStart(); Object last = get(prop); result = super.set(prop, value, flag); <START> if(result) { <END> if (prop == Value.PENALTY_BOX && getPosition() != null) { if ((Boolean)value && getPosition().getFloorPosition() == FloorPosition.JAMMER && team.getLeadJammer().equals(Team.LEAD_LEAD)) { team.setLeadJammer(Team.LEAD_LOST_LEAD); } getPosition().set(Position.Value.PENALTY_BOX, value); } if (getPosition() != null && (prop == Value.NAME || prop == Value.NUMBER || prop == Value.FLAGS)) { scoreBoardChange(new ScoreBoardEvent(getPosition(), Position.Value.valueOf(((Value)prop).name()), value, last)); } if (prop == Value.BASE_ROLE && get(Value.ROLE) == last) { set(Value.ROLE, value); } } requestBatchEnd(); } return result; } }</code><technical_language>Syntax is</technical_language>

Target:
public boolean set(PermanentProperty prop, Object value, Flag flag) { synchronized (coreLock) { boolean result = false; if (prop == Value.POSITION && value instanceof String) { team.field(this, team.getPosition(FloorPosition.fromString((String)value))); } else if (prop == Value.ROLE && value instanceof String) { team.field(this, Role.fromString((String)value)); } else { requestBatchStart(); Object last = get(prop); result = super.set(prop, value, flag); if(result) { if (prop == Value.PENALTY_BOX && getPosition() != null) { if ((Boolean)value && getPosition().getFloorPosition() == FloorPosition.JAMMER && team.getLeadJammer().equals(Team.LEAD_LEAD)) { team.setLeadJammer(Team.LEAD_LOST_LEAD); } getPosition().set(Position.Value.PENALTY_BOX, value); } if (getPosition() != null && (prop == Value.NAME || prop == Value.NUMBER || prop == Value.FLAGS)) { scoreBoardChange(new ScoreBoardEvent(getPosition(), Position.Value.valueOf(((Value)prop).name()), value, last)); } if (prop == Value.BASE_ROLE && get(Value.ROLE) == last) { set(Value.ROLE, value); } if (prop == Value.SORT_PENALTIES && (Boolean)value) { sortPenalties(); } } requestBatchEnd(); } return result; } }
Source:
<code>protected List<ExecutionStatus> getFilteredItems() { ProcessStatusTracker tracker = GeoServerApplication.get().getBeanOfType( ProcessStatusTracker.class); ProcessStatusStore store = tracker.getStore(); Query query = new Query("status", getFilter()); if(count>0) { query.setStartIndex(first); query.setMaxFeatures(count); } SortParam sort = getSort(); if(sort!=null) { SortByImpl[] sortBys = new SortByImpl[1]; final Property<?> property = getProperty(sort); if(property.isSearchable()) { <START> sortBys[0] = new SortByImpl(new PropertyName() { <END> @Override public <T> T evaluate(Object object, Class<T> context) { return null; } @Override public Object evaluate(Object object) { return null; } @Override public Object accept(ExpressionVisitor visitor, Object extraData) { return null; } @Override public String getPropertyName() { return property.getName(); } @Override public NamespaceSupport getNamespaceContext() { return null; } }, SortOrder.ASCENDING); if(sort.isAscending()) { sortBys[0].setSortOrder(SortOrder.ASCENDING); }else { sortBys[0].setSortOrder(SortOrder.DESCENDING); } query.setSortBy(sortBys); } } LOGGER.info("built query "+query+" to filter statuses"); return store.list(query); }</code><technical_language>Confused here, new SortByImple(property.getName()) directly</technical_language>

Target:
protected List<ExecutionStatus> getFilteredItems() { ProcessStatusTracker tracker = GeoServerApplication.get().getBeanOfType( ProcessStatusTracker.class); ProcessStatusStore store = tracker.getStore(); Query query = new Query("status", getFilter()); if(count>0) { query.setStartIndex(first); query.setMaxFeatures(count); } SortParam sort = getSort(); if(sort!=null) { SortByImpl[] sortBys = new SortByImpl[1]; final Property<?> property = getProperty(sort); if(property.isSearchable()) { FF.sort(property.getName(), SortOrder.ASCENDING); if(!sort.isAscending()) { sortBys[0].setSortOrder(SortOrder.DESCENDING); } query.setSortBy(sortBys); } } LOGGER.fine("built query "+query+" to filter statuses"); return store.list(query); }
Source:
<code>public boolean isReadOnly() throws SQLException { checkClosed(); if (!cacheXactState) { ResultSet rs = null; try { rs = execSQLQuery("show transaction_read_only"); if (rs.next()) { String transaction_read_only = rs.getString(1); if ("on".equals(transaction_read_only)) { <START> this.readOnly = true; <END> } else if ("off".equals(transaction_read_only)) { this.readOnly = false; } } } finally { if (rs != null) { rs.close(); } } } LOGGER.log(Level.FINE, " isReadOnly = {0}", this.readOnly); return this.readOnly; }</code><technical_language>this.readOnly = "on".equals(transaction_read_only); enough</technical_language>

Target:
public boolean isReadOnly() throws SQLException { checkClosed(); if (!cacheReadOnlyState) { ResultSet rs = null; try { rs = execSQLQuery("show transaction_read_only"); if (rs.next()) { String transaction_read_only = rs.getString(1); this.readOnly = "on".equals(transaction_read_only); } } finally { if (rs != null) { rs.close(); } } } LOGGER.log(Level.FINE, " isReadOnly = {0}", this.readOnly); return this.readOnly; }
Source:
<code>public void getServiceInvalidConfig() throws Exception { assertThrows(IllegalArgumentException.class, ()-> { <START> OOOMessageHandlerProvider provider = new OOOMessageHandlerProvider(); <END> provider.getService(1L, mock(ServiceConfiguration.class)); }); }</code><technical_language>This line moved out of assertThrows provider.getService() call throw</technical_language>

Target:
public void getServiceInvalidConfig() throws Exception { OOOMessageHandlerProvider provider = new OOOMessageHandlerProvider(); assertThrows(IllegalArgumentException.class, ()-> { provider.getService(1L, mock(ServiceConfiguration.class)); }); }
Source:
<code>protected boolean isLocationAllowed(Rectangle newBounds, Rectangle parentBounds, GraphicalEditPart containerEditpart) { boolean allowed = false; if (null != containerEditpart) { Rectangle absoluteBounds = newBounds.getTranslated(parentBounds.getLocation()); if <START> (null != containerEditpart && <END> containerEditpart.getFigure().getBounds().contains(absoluteBounds)) { allowed = true; } } return allowed; }</code><technical_language>"null != containerEditpart" is checked in outer if</technical_language>

Target:
protected boolean isLocationAllowed(Rectangle newBounds, Rectangle parentBounds, GraphicalEditPart containerEditpart) { boolean allowed = false; if (null != containerEditpart) { Rectangle absoluteBounds = newBounds.getTranslated(parentBounds.getLocation()); if (containerEditpart.getFigure().getBounds().contains(absoluteBounds)) { allowed = true; } } return allowed; }
Source:
<code><START> public void writeToParcel(Parcel dest, int flags) { <END> dest.writeString(getInterfaceName()); dest.writeInt(mLinkAddresses.size()); for(LinkAddress linkAddress : mLinkAddresses) { dest.writeParcelable(linkAddress, flags); } dest.writeInt(mDnses.size()); for(InetAddress d : mDnses) { dest.writeByteArray(d.getAddress()); } dest.writeString(mDomains); dest.writeInt(mRoutes.size()); for(RouteInfo route : mRoutes) { dest.writeParcelable(route, flags); } if (mHttpProxy != null) { dest.writeByte((byte)1); dest.writeParcelable(mHttpProxy, flags); } else { dest.writeByte((byte)0); } ArrayList<LinkProperties> stackedLinks = new ArrayList(mStackedLinks.values()); dest.writeList(stackedLinks); }</code><technical_language>need add mtu parcel/unparcel</technical_language>

Target:
public void writeToParcel(Parcel dest, int flags) { dest.writeString(getInterfaceName()); dest.writeInt(mLinkAddresses.size()); for(LinkAddress linkAddress : mLinkAddresses) { dest.writeParcelable(linkAddress, flags); } dest.writeInt(mDnses.size()); for(InetAddress d : mDnses) { dest.writeByteArray(d.getAddress()); } dest.writeString(mDomains); dest.writeInt(mMtu); dest.writeInt(mRoutes.size()); for(RouteInfo route : mRoutes) { dest.writeParcelable(route, flags); } if (mHttpProxy != null) { dest.writeByte((byte)1); dest.writeParcelable(mHttpProxy, flags); } else { dest.writeByte((byte)0); } ArrayList<LinkProperties> stackedLinks = new ArrayList(mStackedLinks.values()); dest.writeList(stackedLinks); }
Source:
<code>protected void internalReceiveCommand(String itemName, Command command) { logger.debug("internalReceiveCommand() is called!"); for (WemoBindingProvider provider : providers) { String switchFriendlyName = provider.getWemoFriendlyName(itemName); logger.info("item '{}' is configured as '{}'",itemName, switchFriendlyName); } try { if (OnOffType.ON.equals(command)) { logger.trace("Command ON is about to be send to item '{}'",itemName ); boolean onOff = true; sendCommand(itemName, onOff); } else if (OnOffType.OFF.equals(command)) { logger.trace("Command OFF is about to be send to item '{}'",itemName ); boolean onOff = false; sendCommand(itemName, onOff); <START> } <END> } catch (Exception e) { logger.error("Failed to send command", command, e); } }</code><technical_language>simply refer "command" in sendCommand method? "sendCommand(itemName, command)</technical_language>

Target:
protected void internalReceiveCommand(String itemName, Command command) { logger.debug("internalReceiveCommand() is called!"); for (WemoBindingProvider provider : providers) { String switchFriendlyName = provider.getWemoFriendlyName(itemName); logger.info("item '{}' is configured as '{}'",itemName, switchFriendlyName); } try { logger.trace("Command '{}' is about to be send to item '{}'",command, itemName ); sendCommand(itemName, command); } catch (Exception e) { logger.error("Failed to send command", command, e); } }
Source:
<code>private void closeConnection(final PoolEntry poolEntry, final String closureReason) { <START> closeConnection(poolEntry, closureReason, true); <END> }</code><technical_language>Kill parameter closeConnection(), skip calling close(). "penalty" in rare case exception _is_ thrown close() is additional log (at debug level!)</technical_language>

Target:
final void closeConnection(final PoolEntry poolEntry, final String closureReason) { if (connectionBag.remove(poolEntry)) { final int tc = totalConnections.decrementAndGet(); if (tc < 0) { LOGGER.warn("{} - Unexpected value of totalConnections={}", poolName, tc, new Exception()); } final Connection connection = poolEntry.close(); closeConnectionExecutor.execute(new Runnable() { @Override public void run() { quietlyCloseConnection(connection, closureReason); } }); } }
Source:
<code>private static String nextSafeReplacementFilename(String desired, Set<String> existing) { if (! existing.contains(desired)) return desired; for (int counter = 1; counter < 1000; counter++) { int dot = desired.lastIndexOf("."); String candidate = dot >= 0 ? desired.substring(0, dot) + "[" + counter + "]" + desired.substring(dot) : desired + "[" + counter + "]"; if (! existing.contains(candidate)) return candidate; } <START> throw new IllegalStateException("Too many concurrent writes trying to add a file of the saem name!"); <END> }</code><technical_language>spelling</technical_language>

Target:
private static String nextSafeReplacementFilename(String desired, Set<String> existing) { if (! existing.contains(desired)) return desired; for (int counter = 1; counter < 1000; counter++) { int dot = desired.lastIndexOf("."); String candidate = dot >= 0 ? desired.substring(0, dot) + "[" + counter + "]" + desired.substring(dot) : desired + "[" + counter + "]"; if (! existing.contains(candidate)) return candidate; } throw new IllegalStateException("Too many concurrent writes trying to add a file of the same name!"); }