auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
<code>public void clearAllRevisions(String siddhiAppName) { File targetDirectory = new File(folder + File.separator + siddhiAppName); File[] files = targetDirectory.listFiles(); if (files == null || files.length == 0) { <START> log.info("No revisions were found with the Siddhi App " + siddhiAppName); <END> return; } for (File file : files) { if (file.exists()) { if (!file.delete()) { log.error("file is not deleted successfully!"); throw new CannotClearSiddhiAppStateException("Persistence state " + "file is not deleted : " + file.getPath()); } } } }</code><technical_language>"No revisions delete for Siddhi App "</technical_language>

Target:
public void clearAllRevisions(String siddhiAppName) { File targetDirectory = new File(folder + File.separator + siddhiAppName); File[] files = targetDirectory.listFiles(); if (files == null || files.length == 0) { log.info("No revisions were found to delete for the Siddhi App " + siddhiAppName); return; } for (File file : files) { if (file.exists()) { if (!file.delete()) { log.error("file is not deleted successfully : " + file.getName()); throw new CannotClearSiddhiAppStateException("Persistence state " + "file is not deleted : " + file.getName()); } } } }
Source:
<code>public void should_fail_if_try_to_build_settlement_on_existing_settlement() { String userToken1 = loginUser(USER_NAME_1, USER_PASSWORD_1); String userToken2 = loginUser(USER_NAME_2, USER_PASSWORD_2); String userToken3 = loginUser(USER_NAME_3, USER_PASSWORD_3); int gameId = createNewGame(userToken1, false).path("gameId"); int node_id = viewGame(userToken1, gameId).path("map.nodes[0].nodeId"); joinPublicGame(userToken2, gameId); joinPublicGame(userToken3, gameId); setUserReady(userToken1, gameId); setUserReady(userToken2, gameId); setUserReady(userToken3, gameId); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(node_id)) .body("map.nodes[0].building", nullValue()) .body("status", equalTo("PLAYING")); <START> buildSettlement(userToken1, gameId, node_id) <END> .then() .statusCode(200) .body("map.nodes[0].nodeId", is(node_id)) .body("map.nodes[0].building.ownerGameUserId", is(1)) .body("map.nodes[0].building.built", equalTo("SETTLEMENT")) .body("status", equalTo("PLAYING")); buildSettlement(userToken2, gameId, node_id) .then() .statusCode(400) .body("errorCode", equalTo("ERROR")); }</code><technical_language>redundant. more assertions more safety) remove is wish)</technical_language>

Target:
public void should_fail_if_try_to_build_settlement_on_existing_settlement() { String userToken1 = loginUser(USER_NAME_1, USER_PASSWORD_1); String userToken2 = loginUser(USER_NAME_2, USER_PASSWORD_2); String userToken3 = loginUser(USER_NAME_3, USER_PASSWORD_3); int gameId = createNewGame(userToken1, false).path("gameId"); int nodeIdToBuild = viewGame(userToken1, gameId).path("map.nodes[0].nodeId"); int gameUserId1 = viewGame(userToken1, gameId).path("gameUsers[0].id"); joinPublicGame(userToken2, gameId); joinPublicGame(userToken3, gameId); setUserReady(userToken1, gameId); setUserReady(userToken2, gameId); setUserReady(userToken3, gameId); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(nodeIdToBuild)) .body("map.nodes[0].building", nullValue()) .body("status", equalTo("PLAYING")); buildSettlement(userToken1, gameId, nodeIdToBuild) .then() .statusCode(200); viewGame(userToken1, gameId) .then() .statusCode(200) .body("map.nodes[0].nodeId", is(nodeIdToBuild)) .body("map.nodes[0].building.ownerGameUserId", is(gameUserId1)) .body("map.nodes[0].building.built", equalTo("SETTLEMENT")) .body("status", equalTo("PLAYING")); buildSettlement(userToken2, gameId, nodeIdToBuild) .then() .statusCode(400) .body("errorCode", equalTo("ERROR")); }
Source:
<code><START> public static byte[] writeBigDecimal(final BigDecimal num) { <END> if (num == null) { return new byte[0]; } BigInteger sig = new BigInteger(num.unscaledValue().toString()); byte[] sigBytes = sig.toByteArray(); int scale = num.scale(); ByteBuffer bb = ByteBuffer.allocate(sigBytes.length + 8); return bb.putInt(scale).putInt(sigBytes.length).put(sigBytes).array(); }</code><technical_language>I functions fit in VarintUtils, This class is for encoding integers bytes possible, is variable length encoding used. is another class handles BigDecimal serialization org.locationtech.geowave.core.store.data.field.base.BigDecimalSerializationProvider</technical_language>

Target:
public static byte[] writeBigDecimal(final BigDecimal num) { if (num == null) { return new byte[0]; } final byte[] unscaled = num.unscaledValue().toByteArray(); final ByteBuffer buf = ByteBuffer.allocate(VarintUtils.signedIntByteLength(num.scale()) + 4 + unscaled.length); VarintUtils.writeSignedInt(num.scale(), buf); buf.putInt(unscaled.length); buf.put(unscaled); return buf.array(); }
Source:
<code>public LoginPage() { driver = SeleniumDriverManager.getManager().getDriver(); <START> driver.get(baseUrl); <END> PageFactory.initElements(driver, this); }</code><technical_language>change to: driver.get(URL_ADMIN);</technical_language>

Target:
public LoginPage() { driver = SeleniumDriverManager.getManager().getDriver(); driver.get(URL_ADMIN); PageFactory.initElements(driver, this); }
Source:
<code>public void sendOneWay(MessageOut message, int id, InetAddressAndPort to) { if (logger.isTraceEnabled()) logger.trace("{} sending to {}@{}", FBUtilities.getBroadcastAddressAndPort(), message.verb, id, to); if (to.equals(FBUtilities.getBroadcastAddressAndPort())) <START> logger.warn("Message-to-self going over MessagingService", message); <END> for (IMessageSink ms : messageSinks) if (!ms.allowOutgoingMessage(message, id, to)) return; OutboundMessagingPool outboundMessagingPool = getMessagingConnection(to); if (outboundMessagingPool != null) outboundMessagingPool.sendMessage(message, id); }</code><technical_language>NoSpamLogger for key incorporate stack trace rate limit call site separately</technical_language>

Target:
public void sendOneWay(MessageOut message, int id, InetAddressAndPort to) { if (logger.isTraceEnabled()) logger.trace("{} sending to {}@{}", FBUtilities.getBroadcastAddressAndPort(), message.verb, id, to); if (to.equals(FBUtilities.getBroadcastAddressAndPort())) logger.trace("Message-to-self going over MessagingService", message); for (IMessageSink ms : messageSinks) if (!ms.allowOutgoingMessage(message, id, to)) return; OutboundMessagingPool outboundMessagingPool = getMessagingConnection(to); if (outboundMessagingPool != null) outboundMessagingPool.sendMessage(message, id); }
Source:
<code>private void configureRequestInterception() { final Network network = _dts.getNetwork(); network.setRequestInterception(ImmutableList.of(new RequestPattern())); network.onRequestIntercepted(event -> { final URI uri = URI.create(event.getRequest().getUrl()); final String origin = uri.getScheme() + "://" + uri.getAuthority(); final OriginConfig originConfig = _originConfigs.get(origin); <START> if (originConfig == null || !originConfig.isRequestAllowed(uri.getPath())) { <END> System.out.println("Cancelling request to " + uri); network.continueInterceptedRequest( event.getInterceptionId(), ErrorReason.ABORTED, null, null, null, null, null, null ); return; } final ImmutableMap<String, Object> headers = ImmutableMap.<String, Object>builder() .putAll(event.getRequest().getHeaders()) .putAll(originConfig.getAdditionalHeaders()) .build(); network.continueInterceptedRequest( event.getInterceptionId(), null, null, event.getRequest().getUrl(), event.getRequest().getMethod(), event.getRequest().getPostData(), headers, null ); }); }</code><technical_language>nit. I of this logic replaced additional call isNavigationAllowed</technical_language>

Target:
private void configureRequestInterception() { final Network network = _dts.getNetwork(); network.setRequestInterception(ImmutableList.of(new RequestPattern())); network.onRequestIntercepted(event -> { final String url = event.getRequest().getUrl(); if (!_originConfigs.isRequestAllowed(url)) { System.out.println("Cancelling request to " + url); network.continueInterceptedRequest( event.getInterceptionId(), ErrorReason.ABORTED, null, null, null, null, null, null ); return; } final ImmutableMap<String, Object> headers = ImmutableMap.<String, Object>builder() .putAll(event.getRequest().getHeaders()) .putAll(_originConfigs.getAdditionalHeaders(url)) .build(); network.continueInterceptedRequest( event.getInterceptionId(), null, null, url, event.getRequest().getMethod(), event.getRequest().getPostData(), headers, null ); }); }
Source:
<code><START> void setTaskCompletionStatus(boolean status) { <END> taskCompletionStatus = status; }</code><technical_language>I this protected, package access</technical_language>

Target:
protected void setTaskCompletionStatus(boolean status) { taskCompletionStatus = status; }
Source:
<code>private List<ProjectId> fillStorage(int count) { <START> List<ProjectId> ids = newLinkedList(); <END> for (int i = 0; i < count; i++) { ProjectId id = newId(); Project state = givenProject(id, format("project-%d", i)); Any packedState = AnyPacker.pack(state); EntityRecord rawRecord = EntityRecord .newBuilder() .setState(packedState) .setVersion(GivenVersion.withNumber(1)) .build(); EntityRecordWithColumns record = withLifecycleColumns(rawRecord); storage.write(id, record); ids.add(id); } return ids; }</code><technical_language>again</technical_language>

Target:
private List<ProjectId> fillStorage(int count) { List<ProjectId> ids = newArrayListWithCapacity(count); for (int i = 0; i < count; i++) { ProjectId id = newId(); Project state = givenProject(id, format("project-%d", i)); Any packedState = AnyPacker.pack(state); EntityRecord rawRecord = EntityRecord .newBuilder() .setState(packedState) .setVersion(GivenVersion.withNumber(1)) .build(); EntityRecordWithColumns record = withLifecycleColumns(rawRecord); storage.write(id, record); ids.add(id); } return ids; }
Source:
<code>public void MercurySmartBannerTest_001_ButtonName_FixPosition_Close() { SmartBannerComponentObject banner = new SmartBannerComponentObject(driver); wikiURL = urlBuilder.getUrlForWiki(WIKIS[0][0]); banner.openArticleOnWikiByNameWithCbAndNoAds(wikiURL, WIKIS[0][1]); MobileEmulationTouchActions touchActions = new MobileEmulationTouchActions(driver); Assertion.assertTrue( banner.isSmartBannerVisible(), "Smart banner is closed" ); <START> Assertion.assertEquals(banner.isButtonVisible() == true, true, "Button is not visible"); <END> int lastSmartBannerPosition = banner.getSmartBannerPosition(); touchActions.scrollBy(0, 100); boolean result = lastSmartBannerPosition == banner.getSmartBannerPosition(); PageObjectLogging.log( "Position", "is fixed", "is floated", result ); banner.scrollToTopAndWaitForShareBarToBeHidden(); banner.clickCloseButton(); result = !banner.isSmartBannerVisible(); PageObjectLogging.log( "Smart banner", "is closed", "is visible", result ); }</code><technical_language>Assertion.assertTrue(banner.isButtonVisible(), "Button is visible");</technical_language>

Target:
public void MercurySmartBannerTest_001_ButtonName_FixPosition_Close() { SmartBannerComponentObject banner = new SmartBannerComponentObject(driver); wikiURL = urlBuilder.getUrlForWiki(WIKIS[0][0]); banner.openArticleOnWikiByNameWithCbAndNoAds(wikiURL, WIKIS[0][1]); JavascriptActions jsActions = new JavascriptActions(driver); Assertion.assertTrue( banner.isSmartBannerVisible(), "Smart banner is closed" ); Assertion.assertTrue(banner.isButtonVisible(), "Button is not visible"); int lastSmartBannerPosition = banner.getSmartBannerPosition(); jsActions.scrollBy(0, 100); boolean result = lastSmartBannerPosition == banner.getSmartBannerPosition(); PageObjectLogging.log( "Position", "is fixed", "is floated", result ); banner.scrollToTopAndWaitForShareBarToBeHidden(); banner.clickCloseButton(); result = !banner.isSmartBannerVisible(); PageObjectLogging.log( "Smart banner", "is closed", "is visible", result ); }
Source:
<code>public void getUserTransactionsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); <START> return null; <END> } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserTransactions("foobar", new RetrofitPromise<List<Transaction>>()); latch.await(); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/transactions", MOCK_URL)); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Range", "foobar"))); }</code><technical_language>Add newline return</technical_language>

Target:
public void getUserTransactionsShouldReturnTheRequest() throws Exception { final AtomicReference<Request> bodyRef = new AtomicReference<>(); final CountDownLatch latch = new CountDownLatch(1); final RestAdapter adapter = new RestAdapter.Builder().setEndpoint(MOCK_URL).setClient(new Client() { @Override public Response execute(Request request) throws IOException { bodyRef.set(request); latch.countDown(); return null; } }).build(); final UserService userService = adapter.create(UserService.class); userService.getUserTransactions("foobar", new RetrofitPromise<List<Transaction>>()); latch.await(); Assert.assertEquals(bodyRef.get().getMethod(), "GET"); Assert.assertEquals(bodyRef.get().getUrl(), String.format("%s/v0/me/transactions", MOCK_URL)); Assert.assertTrue(bodyRef.get().getHeaders().contains(new Header("Range", "foobar"))); }
Source:
<code>synchronized void connect() { RestHighLevelClient me = client; if (me == null) { synchronized (ElasticSearchAuditDestination.class) { me = client; if (client == null) { String urls = PropertiesUtil.getProperty("ranger.audit.solr.url"); String protocol = getProperty("ranger.audit.solr.url", "http"); int port = Integer.parseInt(getProperty("ranger.audit.solr.port", "8080")); if (urls != null) { urls = urls.trim(); } if (urls != null && urls.equalsIgnoreCase("NONE")) { urls = null; } try { me = client = new RestHighLevelClient( RestClient.builder( MiscUtil.toArray(urls, ",").stream() .map(x -> new HttpHost(x, port, protocol)) .<HttpHost>toArray(i -> new HttpHost[i]) )); ; } catch (Throwable t) { <START> logger.fatal("Can't connect to Solr server. urls=" + urls, t); <END> } } } } }</code><technical_language>Replace Solr Elastic search</technical_language>

Target:
synchronized void connect() { if (client == null) { synchronized (ElasticSearchAuditDestination.class) { if (client == null) { String urls = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_URLS); String protocol = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PROTOCOL, "http"); String user = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_USER, ""); String password = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PWRD, ""); int port = Integer.parseInt(PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_PORT, "9200")); this.index = PropertiesUtil.getProperty(CONFIG_PREFIX + "." + CONFIG_INDEX, "audit"); logger.warn(String.format("Initializing ElasticSearch (URLs: %s; Protocol: %s; Port: %s)", urls, protocol, port)); if (urls != null) { urls = urls.trim(); } if (urls != null && urls.equalsIgnoreCase("NONE")) { logger.warn(String.format("Clearing URI config value: %s", urls)); urls = null; } try { final CredentialsProvider credentialsProvider; if(!user.isEmpty()) { credentialsProvider = new BasicCredentialsProvider(); credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, password)); } else { credentialsProvider = null; } client = new RestHighLevelClient( RestClient.builder( MiscUtil.toArray(urls, ",").stream() .map(x -> new HttpHost(x, port, protocol)) .<HttpHost>toArray(i -> new HttpHost[i]) ).setHttpClientConfigCallback(clientBuilder -> (credentialsProvider != null) ? clientBuilder.setDefaultCredentialsProvider(credentialsProvider) : clientBuilder)); } catch (Throwable t) { logger.fatal("Can't connect to ElasticSearch server" + "." + " urls=" + urls, t); } } } } }
Source:
<code>public void testNumberItemScale() throws BindingConfigParseException { String bindingConfig = "kaku#outside:weather,property=temperature"; PilightBindingConfig config = provider.parseBindingConfig(testItem, bindingConfig); Assert.assertNotNull(config); DecimalType number0 = (DecimalType) binding.getState("23", config); Assert.assertEquals(number0.toBigDecimal().compareTo(new BigDecimal("23")), 0); config.setScale(1); DecimalType number1 = (DecimalType) binding.getState("23.3", config); Assert.assertEquals(number1.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); config.setScale(0); DecimalType number2 = (DecimalType) binding.getState("2.3", config); <START> Assert.assertEquals(number2.toBigDecimal().compareTo(new BigDecimal("23")), 0); <END> config.setScale(2); DecimalType number3 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number3.toBigDecimal().compareTo(new BigDecimal("2.33")), 0); config.setScale(-1); DecimalType number4 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number4.toBigDecimal().compareTo(new BigDecimal("2330")), 0); config.setScale(1); DecimalType number5 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number5.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); }</code><technical_language>i if test correctly. 2.3 return "2" scale "0", it</technical_language>

Target:
public void testNumberItemScale() throws BindingConfigParseException { String bindingConfig = "kaku#outside:weather,property=temperature"; PilightBindingConfig config = provider.parseBindingConfig(testItem, bindingConfig); Assert.assertNotNull(config); DecimalType number0 = (DecimalType) binding.getState("23", config); Assert.assertEquals(number0.toBigDecimal().compareTo(new BigDecimal("23")), 0); config.setScale(1); DecimalType number1 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number1.toBigDecimal().compareTo(new BigDecimal("23.3")), 0); config.setScale(2); DecimalType number2 = (DecimalType) binding.getState("2233", config); Assert.assertEquals(number2.toBigDecimal().compareTo(new BigDecimal("22.33")), 0); config.setScale(-1); DecimalType number3 = (DecimalType) binding.getState("233", config); Assert.assertEquals(number3.toBigDecimal().compareTo(new BigDecimal("2330")), 0); }
Source:
<code>public void notifyChanged(Notification notification) { <START> final int eventType = notification.getEventType(); <END> if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }</code><technical_language>this field is final ? is in method scope</technical_language>

Target:
public void notifyChanged(Notification notification) { int eventType = notification.getEventType(); if (eventType == StereotypeExtensionNotification.STEREOTYPE_APPLIED_TO_ELEMENT) { initialisation(); refreshNotationStructure(); } else if (eventType == StereotypeExtensionNotification.STEREOTYPE_UNAPPLIED_FROM_ELEMENT) { initialisation(); refreshNotationStructure(); } }
Source:
<code>public void shouldCheckpointEvenIfNoChanges() throws Exception { CheckpointCounter checkpointCounter = new CheckpointCounter(); try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); for ( int i = 0; i < 2; i++ ) { <START> } <END> index.checkpoint( unlimited() ); assertEquals( 1, checkpointCounter.count() ); } }</code><technical_language>Empty loop</technical_language>

Target:
public void shouldCheckpointEvenIfNoChanges() throws Exception { CheckpointCounter checkpointCounter = new CheckpointCounter(); try ( GBPTree<MutableLong,MutableLong> index = index().with( checkpointCounter ).build() ) { checkpointCounter.reset(); index.checkpoint( unlimited() ); assertEquals( 1, checkpointCounter.count() ); } }
Source:
<code>public static void importProject(Project project, String projectName, File projectRoot) throws IOException, ConfigurationException { GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); projectImporter.importProject(projectName, projectRoot, false, new GradleSyncListener() { @Override public void syncStarted(@NotNull Project project) { } @Override public void syncEnded(@NotNull Project project) { } @Override public void syncFailed(@NotNull Project project, @NotNull final String errorMessage) { fail(errorMessage); } }, project, <START> null); <END> }</code><technical_language>nit: remove arg</technical_language>

Target:
public static void importProject(Project project, String projectName, File projectRoot) throws IOException, ConfigurationException { GradleProjectImporter projectImporter = GradleProjectImporter.getInstance(); boolean generateSources = false; projectImporter.importProject(projectName, projectRoot, generateSources, new GradleSyncListener() { @Override public void syncStarted(@NotNull Project project) { } @Override public void syncEnded(@NotNull Project project) { } @Override public void syncFailed(@NotNull Project project, @NotNull final String errorMessage) { fail(errorMessage); } }, project, null); }
Source:
<code>public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } else { output = null; } } else if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { try { ParcelFileDescriptor parcelFileDescriptor = <START> getActivity().getContentResolver().openFileDescriptor(data.getData(), getString(R.string.file_read_mode)); <END> FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); patientPhoto = image; Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } catch (Exception e) { logger.e(getString(R.string.gallery_image_request_failed_message), e); } } }</code><technical_language>Place in ApplicationConstants instead</technical_language>

Target:
public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == IMAGE_REQUEST) { if (resultCode == Activity.RESULT_OK) { patientPhoto = getResizedPortraitImage(output.getPath()); Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } else { output = null; } } else if (requestCode == GALLERY_IMAGE_REQUEST && resultCode == Activity.RESULT_OK) { try { ParcelFileDescriptor parcelFileDescriptor = getActivity().getContentResolver().openFileDescriptor(data.getData(), ApplicationConstants.READ_MODE); FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor(); Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor); parcelFileDescriptor.close(); patientPhoto = image; Bitmap bitmap = ThumbnailUtils.extractThumbnail(patientPhoto, patientImageView.getWidth(), patientImageView.getHeight()); patientImageView.setImageBitmap(bitmap); patientImageView.invalidate(); } catch (Exception e) { logger.e("Error getting image from gallery.", e); } } }
Source:
<code>private HttpUriRequest buildRequest(String endpoint, String token) { HttpGet request = new HttpGet(endpoint); <START> request.addHeader("User-Agent", "openshift-resetclient-java"); <END> request.addHeader("Authorization", "Bearer " + token); return request; }</code><technical_language>openshift-restclient-java</technical_language>

Target:
private HttpUriRequest buildRequest(String endpoint, String token) { HttpGet request = new HttpGet(endpoint); request.addHeader("User-Agent", "openshift-restclient-java"); request.addHeader("Authorization", "Bearer " + token); return request; }
Source:
<code>public void connect() throws IOException { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (CacheClosedException ex) { LOG.info("error initiating client ", ex); } region = clientCache.getRegion(getRegionName()); <START> <END> if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create( getRegionName()); } }</code><technical_language>This throw NPE if CacheClosedException is thrown initialization of clientCache</technical_language>

Target:
public void connect() throws IOException { try { clientCache = new ClientCacheFactory().addPoolLocator(getLocatorHost(), getLocatorPort()).create(); } catch (Exception ex) { throw new RuntimeException(ex); } region = clientCache.getRegion(getRegionName()); if (region == null) { region = clientCache.<Object, Object> createClientRegionFactory(ClientRegionShortcut.PROXY).create( getRegionName()); } }
Source:
<code><START> public void setSessionLifetime(int lifetime) { <END> sessionLifetime = lifetime; }</code><technical_language>synchronized</technical_language>

Target:
public synchronized void setSessionLifetime(int lifetime) { sessionLifetime = lifetime; }
Source:
<code>public void testRemove() throws Exception { final IgniteCache<Integer, Integer> cache = grid(2).getOrCreateCache(getConfig()); GridTestSafeThreadFactory factory = new GridTestSafeThreadFactory(cacheMode().name()+"_remove"); for (TransactionConcurrency concurrency : TransactionConcurrency.values()) for (TransactionIsolation isolation : TransactionIsolation.values()) { cache.put(1, 1); try (Transaction tx = grid(2).transactions().txStart(concurrency, isolation)) { info(concurrency + " " + isolation); tx.savepoint("sp"); assertTrue(cache.remove(1)); <START> Thread t = factory.newThread(new Runnable() { <END> @Override public void run() { assertTrue(cache.remove(1, 1)); } }); t.start(); if (concurrency == TransactionConcurrency.PESSIMISTIC) while (t.getState() != Thread.State.WAITING) factory.checkError(); tx.rollbackToSavepoint("sp"); t.join(3_000); assertEquals("Broken multithreaded rollback to savepoint in " + concurrency + " " + isolation + " transaction.", null, cache.get(1)); tx.commit(); } assertEquals("Broken rollback to savepoint in " + concurrency + " " + isolation + " transaction.", null, cache.get(1)); } }</code><technical_language>factory.newThread is internal method, in tests it. org.apache.ignite.testframework.GridTestUtils#runMultiThreadedAsync(java.util.concurrent.Callable<?>, int, java.lang.String) instead</technical_language>

Target:
public void testRemove() { executeTestForAllCaches( new CIX3<NodeCombination, IgniteCache<Integer, Integer>, CacheConfiguration<Integer, Integer>>() { @Override public void applyx( NodeCombination nodes, IgniteCache<Integer, Integer> cache, CacheConfiguration<Integer, Integer> cfg) throws IgniteCheckedException { int key = generateKey(cfg, nodes.primaryForKey()); IgniteCache<Integer, Integer> cacheAsync = nodes.anotherTxOwner().getOrCreateCache(cfg); for (TxType txType : txTypes) { info("Transaction type " + txType); cache.put(key, 1); try (Transaction tx = nodes.txOwner().transactions().txStart(txType.concurrency, txType.isolation)) { tx.savepoint("sp"); assertTrue(cache.remove(key)); IgniteInternalFuture fut = GridTestUtils.runAsync( () -> assertTrue(cacheAsync.remove(key, 1)), "_remove"); waitForSecondCandidate(txType.concurrency, nodes.primaryForKey(), cache, cacheAsync, key); tx.rollbackToSavepoint("sp"); fut.get(FUT_TIMEOUT); assertEquals("Broken multithreaded rollback to savepoint in " + txType.concurrency + ' ' + txType.isolation + " transaction.", null, cache.get(key)); tx.commit(); } assertEquals("Broken rollback to savepoint in " + txType.concurrency + ' ' + txType.isolation + " transaction.", null, cache.get(key)); } }}); }
Source:
<code>public String internalFragment() { ResolvedType resolvedType = getResolvedType(); if (resolvedType instanceof XmlSchemaExternalType) { <START> return ((XmlSchemaExternalType) resolvedType).getInternalFragment(); <END> } else { return null; } }</code><technical_language>this AbstractExternalType works Json</technical_language>

Target:
public String internalFragment() { ResolvedType resolvedType = getResolvedType(); if (resolvedType instanceof AbstractExternalType) { return ((AbstractExternalType) resolvedType).getInternalFragment(); } else { return null; } }
Source:
<code>public void setUp() throws IOException { EmittingLogger.registerEmitter(new NoopServiceEmitter()); druidLeaderClient = EasyMock.createMock(DruidLeaderClient.class); config = createMock(LookupListeningAnnouncerConfig.class); lookupExtractorFactory = new MapLookupExtractorFactory( ImmutableMap.<String, String>of( "key", "value" ), true ); container = new LookupExtractorFactoryContainer("v0", lookupExtractorFactory); mapper.registerSubtypes(MapLookupExtractorFactory.class); String temporaryPath = temporaryFolder.newFolder().getAbsolutePath(); lookupReferencesManager = new LookupReferencesManager( <START> new LookupConfig() <END> { @Override public boolean getEnableLookupSyncOnStartup() { return true; } @Override public String getSnapshotWorkingDir() { return temporaryPath; } }, mapper, druidLeaderClient, config, true ); }</code><technical_language>Turns out this change is net negative code brevity of tests, for suggesting it, I suggest roll back, sense</technical_language>

Target:
public void setUp() throws IOException { EmittingLogger.registerEmitter(new NoopServiceEmitter()); druidLeaderClient = EasyMock.createMock(DruidLeaderClient.class); config = createMock(LookupListeningAnnouncerConfig.class); lookupExtractorFactory = new MapLookupExtractorFactory( ImmutableMap.<String, String>of( "key", "value" ), true ); container = new LookupExtractorFactoryContainer("v0", lookupExtractorFactory); mapper.registerSubtypes(MapLookupExtractorFactory.class); String temporaryPath = temporaryFolder.newFolder().getAbsolutePath(); lookupReferencesManager = new LookupReferencesManager( new LookupConfig(temporaryFolder.newFolder().getAbsolutePath()), mapper, druidLeaderClient, config, true ); }
Source:
<code>public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true); <START> } <END></code><technical_language>Add message telling people builder</technical_language>

Target:
public Request(URI uri, String method, ListMultimap<String, String> headers, BodyGenerator bodyGenerator) { this(uri, method, headers, bodyGenerator, true, false); }
Source:
<code>public void closeConnection(NetworkRequest originalRequest) throws InterruptedException { <START> throw new NotImplementedException(); <END> }</code><technical_language>Prefer UnsupportedOperationException NotImplementedException. NotImplementedException sun packages JVM implementation specific. Also, this supported calling originalRequest.getRestResponseChannel().close()? Feel free do this in a future PR too</technical_language>

Target:
public void closeConnection(NetworkRequest originalRequest) throws InterruptedException { throw new UnsupportedOperationException(); }
Source:
<code>public Side getEffectiveSide() { Thread thr = Thread.currentThread(); <START> if (thr.getName().equals("Server thread") || thr.getName().startsWith("Netty Epoll Server IO") || thr.getName().startsWith("Netty Server IO")) <END> { return Side.SERVER; } return Side.CLIENT; }</code><technical_language>thr.getName().contains("Server")</technical_language>

Target:
public Side getEffectiveSide() { final ThreadGroup group = Thread.currentThread().getThreadGroup(); return group instanceof SidedThreadGroup ? ((SidedThreadGroup) group).getSide() : Side.CLIENT; }
Source:
<code>public void fileSystemLimit() throws RocksDBException { RocksDB.loadLibrary(); final File persistedCacheLocation = new File("/tmp/", "diskBackedMap"); SstFileManager sstFileManager = new SstFileManager(Env.getDefault()); sstFileManager.setMaxAllowedSpaceUsage(FileUtils.ONE_KB); sstFileManager.setCompactionBufferSize(FileUtils.ONE_KB); final Options options = new Options().setCreateIfMissing(true) .setSstFileManager(sstFileManager) .setWriteBufferSize(FileUtils.ONE_KB); CorfuTable<String, String> table = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) <START> .setArguments(new RocksDbStreamingMap<String, String>( <END> persistedCacheLocation, options, Serializers.JSON, getRuntime())) .setStreamName("diskBackedMap") .open(); final long ITERATION_COUNT = 100000; final int ENTITY_CHAR_SIZE = 1000; assertThatThrownBy(() -> LongStream.rangeClosed(1, ITERATION_COUNT).forEach(idx -> { String key = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); String value = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); table.put(key, value); String persistedValue = table.get(key); Assertions.assertEquals(value, persistedValue); })).isInstanceOf(UnrecoverableCorfuError.class) .hasCauseInstanceOf(RocksDBException.class); }</code><technical_language>I move naming RocksDB. If change technology a implementation in future, clients change this. PersistedStreamingMap that</technical_language>

Target:
public void fileSystemLimit() throws RocksDBException { RocksDB.loadLibrary(); final File persistedCacheLocation = new File("/tmp/", "diskBackedMap"); SstFileManager sstFileManager = new SstFileManager(Env.getDefault()); sstFileManager.setMaxAllowedSpaceUsage(FileUtils.ONE_KB); sstFileManager.setCompactionBufferSize(FileUtils.ONE_KB); final Options options = new Options().setCreateIfMissing(true) .setSstFileManager(sstFileManager) .setWriteBufferSize(FileUtils.ONE_KB); CorfuTable<String, String> table = getDefaultRuntime().getObjectsView().build() .setTypeToken(new TypeToken<CorfuTable<String, String>>() {}) .setArguments(new PersistedStreamingMap<String, String>( persistedCacheLocation, options, Serializers.JSON, getRuntime())) .setStreamName("diskBackedMap") .open(); final long ITERATION_COUNT = 100000; final int ENTITY_CHAR_SIZE = 1000; assertThatThrownBy(() -> LongStream.rangeClosed(1, ITERATION_COUNT).forEach(idx -> { String key = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); String value = RandomStringUtils.random(ENTITY_CHAR_SIZE, true, true); table.put(key, value); String persistedValue = table.get(key); Assertions.assertEquals(value, persistedValue); })).isInstanceOf(UnrecoverableCorfuError.class) .hasCauseInstanceOf(RocksDBException.class); }
Source:
<code>private static List<String> mediaCellValues(String value, boolean useQuestionId, String imagePrefix) { List<String> cells = new ArrayList<>(); if (value.startsWith("{")) { Media media = MediaResponse.parse(value); String filename = media.getFilename(); final int filenameIndex = filename != null ? filename.lastIndexOf("/") + 1 : -1; if (filenameIndex > 0 && filenameIndex < filename.length()) { <START> cells.add(imagePrefix + filename.substring(filenameIndex)); <END> if (useQuestionId && media.getLocation() != null) { cells.add(Double.toString(media.getLocation().getLatitude())); cells.add(Double.toString(media.getLocation().getLongitude())); cells.add(Double.toString(media.getLocation().getAccuracy())); } } } else if (!value.isEmpty()) { cells.add(ExportImportUtils.formatImage(imagePrefix, value)); } return cells; }</code><technical_language>line 735 is whats happening in ExportImportUtils.formatImage(). I propose eliminate of ExportImportUtils.formatImage() simpler? need branches. if branch for case geolocation is present</technical_language>

Target:
private static List<String> mediaCellValues(String value, boolean useQuestionId, String imagePrefix) { List<String> cells = new ArrayList<>(); Media media = MediaResponse.parse(value); String filename = media.getFilename(); final int filenameIndex = filename != null ? filename.lastIndexOf("/") + 1 : -1; if (filenameIndex > 0 && filenameIndex < filename.length()) { cells.add(imagePrefix + filename.substring(filenameIndex)); if (useQuestionId && media.getLocation() != null) { cells.add(Double.toString(media.getLocation().getLatitude())); cells.add(Double.toString(media.getLocation().getLongitude())); cells.add(Double.toString(media.getLocation().getAccuracy())); } } return cells; }
Source:
<code>public void testEndOfYearDates() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); cal.set(2015, 11, 30, 12, 0, 0); Date date = cal.getTime(); assertEquals("30/12/2015", TimeHelper.formatDate(date)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(date)); assertEquals("Wed, 30 Dec 2015, 12:00 PM UTC", TimeHelper.formatDateTimeForComments(date)); <START> assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage(date)); <END> }</code><technical_language>midnight? Is special behaviour for it</technical_language>

Target:
public void testEndOfYearDates() { Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC")); cal.clear(); cal.set(2015, 11, 30, 12, 0, 0); Date date = cal.getTime(); assertEquals("30/12/2015", TimeHelper.formatDate(date)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON", TimeHelper.formatTime12H(date)); assertEquals("Wed, 30 Dec 2015, 12:00 NOON UTC", TimeHelper.formatDateTimeForComments(date)); assertEquals("30 Dec 12:00 NOON", TimeHelper.formatDateTimeForInstructorHomePage(date)); }
Source:
<code>public VDS activate() { VDS vds = null; try { refreshHost(vds); <START> } catch (java.lang.Exception e) { <END> log.infoFormat("Failed to activate VDS = {0} with error: {1}.", getVdsId(), e.getMessage()); } return vds; }</code><technical_language>prefix of full package name java.lang. is redundant</technical_language>

Target:
public VDS activate() { VDS vds = null; try { refreshHost(vds); } catch (Exception e) { log.infoFormat("Failed to activate VDS = {0} with error: {1}.", getVdsId(), e.getMessage()); } return vds; }
Source:
<code>private void update(GitResourceVariantTreeSubscriber subscriber, RepositoryMapping which) { for (GitSynchronizeData gsd : gsds) { if (which.getRepository().equals(gsd.getRepository())) { try { gsd.updateRevs(); } catch (IOException e) { <START> Activator.error("Failed refresh Rev's", e); END> return; } subscriber.reset(this.gsds); ResourceTraversal[] traversals = getScopeManager().getScope() .getTraversals(); try { subscriber.refresh(traversals, new NullProgressMonitor()); } catch (CoreException e) { Activator.error("Failed refresh synchronize view", e); } return; } } }</code><technical_language>externalize error messages too</technical_language>

Target:
private void update(GitResourceVariantTreeSubscriber subscriber, RepositoryMapping which) { for (GitSynchronizeData gsd : gsds) { if (which.getRepository().equals(gsd.getRepository())) { try { gsd.updateRevs(); } catch (IOException e) { Activator.error( CoreText.GitSubscriberMergeContext_FailedFetchRefs, e); return; } subscriber.reset(this.gsds); ResourceTraversal[] traversals = getScopeManager().getScope() .getTraversals(); try { subscriber.refresh(traversals, new NullProgressMonitor()); } catch (CoreException e) { Activator .error(CoreText.GitSubscriberMergeContext_FailedRefreshSyncView, e); } return; } } }
Source:
<code><START> @Override public void clearAllEvents() { <END> getCallsHandler().executeModification("ClearAllAuditLogs", getCustomMapSqlParameterSource()); }</code><technical_language>I pretty convention is @Override method declaration for of these</technical_language>

Target:
public void clearAllEvents() { getCallsHandler().executeModification("ClearAllAuditLogs", getCustomMapSqlParameterSource()); }
Source:
<code>public Document getPayload() { Document document = new Document((ObjectNode) this.get(PayloadPropertyName)); if (document == null) { throw new IllegalStateException("Underlying object does not have an 'payload' field."); <START> } <END> return document; }</code><technical_language>nit: extra line if</technical_language>

Target:
public Document getPayload() { if (!this.has(PAYLOAD_PROPERTY_NAME)) { throw new IllegalStateException("Underlying object does not have an 'payload' field."); } return new Document((ObjectNode) this.get(PAYLOAD_PROPERTY_NAME)); }
Source:
<code><START> public String toString() { <END> String prefix = "-l" + level + "-" + type; String cmdline = prefix + "size" + " " + size + " "; cmdline += prefix + "bsize" + " " + bsize + " "; if(assoc > 0) cmdline += prefix + "assoc" + " " + assoc + " "; if(ccc) cmdline += prefix + "ccc" + " "; return cmdline; }</code><technical_language>Consider StringBuilder instead of simple string concatenation, allocates new strings time a concatenation is done</technical_language>

Target:
public String toString() { StringBuilder cacheConfig = new StringBuilder(); try { String prefix = "-l" + level + "-" + type; cacheConfig.append("prefix"); String cmdline = prefix + "size" + " " + size + " "; cacheConfig.append("cmdline"); cmdline += prefix + "bsize" + " " + bsize + " "; if(assoc > 0) cmdline += prefix + "assoc" + " " + assoc + " "; if(ccc) cmdline += prefix + "ccc" + " "; cacheConfig.append("cmdline"); return cmdline; } catch (Exception e) { return(""); } }
Source:
<code><START> static public void assertEquals(byte[] actual, byte[] expected) { <END> assertEquals(actual, expected, ""); }</code><technical_language>public static sonar complain</technical_language>

Target:
public static void assertEquals(byte[] actual, byte[] expected) { assertEquals(actual, expected, ""); }
Source:
<code>public InMoovGui(final String boundServiceName, final SwingGui myService) { super(boundServiceName, myService); Font f = new Font("SansSerif", Font.BOLD, 20); JPanel generalPanel = new JPanel(); add(inmoovPane); generalPanel.setBackground(Color.WHITE); ImageIcon generalIcon = Util.getImageIcon("InMoov.png"); inmoovPane.addTab("General", generalIcon, generalPanel); generalPanel.setLayout(new GridLayout(3, 2, 0, 0)); lblNewLabel_1.setForeground(Color.RED); <START> generalPanel.add(lblNewLabel_1); <END> generalPanel.add(lblNewLabel_2); JLabel lblNewLabel = new JLabel(" Language : "); generalPanel.add(lblNewLabel); for (Entry<String, String> e : InMoov.languages.entrySet()) { comboLanguage.addItem(e.getValue()); } generalPanel.add(comboLanguage); JLabel MuteLabel = new JLabel("Mute startup :"); generalPanel.add(MuteLabel); muteCheckBox.setHorizontalAlignment(SwingConstants.CENTER); generalPanel.add(muteCheckBox); JPanel visionPanel = new JPanel(); visionPanel.setBackground(Color.WHITE); ImageIcon visionIcon = Util.getImageIcon("OpenCV.png"); inmoovPane.addTab("Vision", visionIcon, visionPanel); visionPanel.setLayout(new GridLayout(3, 2, 0, 0)); visionPanel.add(startVision); visionPanel.add(configureVision); JLabel visionLabel = new JLabel("Enable OpenCV :"); visionPanel.add(visionLabel); visionPanel.add(enableOpenCV); visionPanel.add(lblFlipCamera); visionPanel.add(panel); panel.add(Flip); panel.add(PyramidDown); restoreListeners(); }</code><technical_language>If local this method labels added members class</technical_language>

Target:
public InMoovGui(final String boundServiceName, final SwingGui myService) { super(boundServiceName, myService); Font f = new Font("SansSerif", Font.BOLD, 20); JPanel generalPanel = new JPanel(); add(inmoovPane); generalPanel.setBackground(Color.WHITE); ImageIcon generalIcon = Util.getImageIcon("InMoov.png"); inmoovPane.addTab("General", generalIcon, generalPanel); generalPanel.setLayout(new GridLayout(3, 2, 0, 0)); notReadyLabel1.setForeground(Color.RED); generalPanel.add(notReadyLabel1); generalPanel.add(notReadyLabel2); JLabel lblNewLabel = new JLabel(" Language : "); generalPanel.add(lblNewLabel); for (Entry<String, String> e : InMoov.languages.entrySet()) { comboLanguage.addItem(e.getValue()); } generalPanel.add(comboLanguage); JLabel MuteLabel = new JLabel("Mute startup :"); generalPanel.add(MuteLabel); muteCheckBox.setHorizontalAlignment(SwingConstants.CENTER); generalPanel.add(muteCheckBox); JPanel visionPanel = new JPanel(); visionPanel.setBackground(Color.WHITE); ImageIcon visionIcon = Util.getImageIcon("OpenCV.png"); inmoovPane.addTab("Vision", visionIcon, visionPanel); visionPanel.setLayout(new GridLayout(3, 2, 0, 0)); visionPanel.add(startVision); visionPanel.add(configureVision); JLabel visionLabel = new JLabel("Enable OpenCV :"); visionPanel.add(visionLabel); visionPanel.add(enableOpenCV); visionPanel.add(lblFlipCamera); visionPanel.add(panel); panel.add(Flip); panel.add(PyramidDown); restoreListeners(); }
Source:
<code>public void moveDownEnd(Database db, MolgenisRequest t) throws MatrixException { if (this.matrix instanceof DatabaseMatrix) { ((DatabaseMatrix) this.matrix).setDatabase(db); } <START> if (!this.matrix.getRowCount().equals(0)) <END> { this.matrix.setRowOffset((matrix.getRowCount() % matrix.getRowLimit() == 0 ? new Double(matrix .getRowCount() / matrix.getRowLimit()).intValue() - 1 : new Double(matrix.getRowCount() / matrix.getRowLimit()).intValue()) * matrix.getRowLimit()); } }</code><technical_language>Suggestion: replace if (this.matrix.getRowCount() > 0)</technical_language>

Target:
public void moveDownEnd(Database db, MolgenisRequest t) throws MatrixException { if (this.matrix instanceof DatabaseMatrix) { ((DatabaseMatrix) this.matrix).setDatabase(db); } if (this.matrix.getRowCount() > 0) { this.matrix.setRowOffset((matrix.getRowCount() % matrix.getRowLimit() == 0 ? new Double(matrix .getRowCount() / matrix.getRowLimit()).intValue() - 1 : new Double(matrix.getRowCount() / matrix.getRowLimit()).intValue()) * matrix.getRowLimit()); } }
Source:
<code>public NotificationsClient(String hookURL, String uuid) { this.hookURL = hookURL; this.uuid = uuid; boolean invalidHookURL = (hookURL == null || hookURL.isEmpty()); boolean invalidUUID = (uuid == null || uuid.isEmpty()); if (invalidHookURL || invalidUUID) { <START> disabled = true; <END> if (!invalidUUID) { System.err.println("Notifications UUID is specified but no notifications webhook URL found in config file"); } } }</code><technical_language>Sorry, forgot mention time. If a uuid is provided, generate one</technical_language>

Target:
public NotificationsClient(String hookURL, String uuid) { boolean invalidHookURL = (hookURL == null || hookURL.isEmpty()); boolean invalidUUID = (uuid == null || uuid.isEmpty()); if (invalidHookURL) { if (!invalidUUID) { ArgumentUtility.errorMessage("Notifications UUID is specified but no notifications webhook URL found in config file. Aborting launch.", Client.CLIENT_ERROR); } disabled = true; } else { if (invalidUUID) { uuid = UUID.randomUUID().toString(); System.out.println("The UUID generated for this specific execution is " + uuid); } this.hookURL = hookURL; this.uuid = uuid; } }