auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
public FileStore fileStore() { String currentDir = System.getProperty("user.dir"); if (!currentDir.endsWith(File.separator)) { currentDir = currentDir + File.separator; } String molgenisFileStoreDirStr = currentDir + "data" + File.separator + "filestore"; File molgenisDataDir = new File(molgenisFileStoreDirStr); if (!molgenisDataDir.exists() && !molgenisDataDir.mkdirs()) { throw new RuntimeException("failed to create directory: " + molgenisFileStoreDirStr); } return new FileStore(molgenisFileStoreDirStr); }

Target:
public FileStore fileStore() { String currentDir = System.getProperty("java.io.tmpdir") + File.separator + UUID.randomUUID() .toString() .replaceAll("-", ""); if (!currentDir.endsWith(File.separator)) { currentDir = currentDir + File.separator; } String molgenisFileStoreDirStr = currentDir + "data" + File.separator + "filestore"; File molgenisDataDir = new File(molgenisFileStoreDirStr); if (!molgenisDataDir.exists() && !molgenisDataDir.mkdirs()) { throw new RuntimeException("failed to create directory: " + molgenisFileStoreDirStr); } return new FileStore(molgenisFileStoreDirStr); }
Source:
public void onLocationChanged(Location location) { this.location = toGeoPointData(location); Log.i("HereFunctionHandler", "location has been set to " + this.location.getDisplayText()); if (this.location.getAccuracy() <= GeoUtils.ACCEPTABLE_ACCURACY) { locationGoodEnough = true; forbidGpsUse(); } if (entitySelectActivity != null) { entitySelectActivity.onLocationChanged(); } }

Target:
public void onLocationChanged(Location location) { this.location = toGeoPointData(location); Log.i("HereFunctionHandler", "location has been set to " + this.location.getDisplayText()); if (this.location.getAccuracy() <= GeoUtils.ACCEPTABLE_ACCURACY) { locationGoodEnough = true; forbidGpsUse(); } if (entitySelectActivity != null) { entitySelectActivity.onEvalLocationChanged(); } }
Source:
private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { if (mBackStack.isEmpty()) { mBackStack.add(new NavBackStackEntry(mGraph, finalArgs)); } ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavDestination destination = newDest; while (destination != null && findDestination(destination.getId()) == null) { NavGraph parent = destination.getParent(); if (parent != null) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); if (!node.getNavigatorName().equals(parent.getNavigatorName())) { Navigator<NavGraph> parentNavigator = mNavigatorProvider.getNavigator( parent.getNavigatorName()); parentNavigator.navigate(parent, finalArgs, navOptions, navigatorExtras); navigator.popBackStack(); } } destination = parent; } mBackStack.addAll(hierarchy); NavBackStackEntry newBackStackEntry = new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs)); mBackStack.add(newBackStackEntry); } updateOnBackPressedCallbackEnabled(); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }

Target:
private void navigate(@NonNull NavDestination node, @Nullable Bundle args, @Nullable NavOptions navOptions, @Nullable Navigator.Extras navigatorExtras) { boolean popped = false; if (navOptions != null) { if (navOptions.getPopUpTo() != -1) { popped = popBackStackInternal(navOptions.getPopUpTo(), navOptions.isPopUpToInclusive()); } } Navigator<NavDestination> navigator = mNavigatorProvider.getNavigator( node.getNavigatorName()); Bundle finalArgs = node.addInDefaultArgs(args); NavDestination newDest = navigator.navigate(node, finalArgs, navOptions, navigatorExtras); if (newDest != null) { if (mBackStack.isEmpty()) { mBackStack.add(new NavBackStackEntry(mGraph, finalArgs)); } ArrayDeque<NavBackStackEntry> hierarchy = new ArrayDeque<>(); NavDestination destination = newDest; while (destination != null && findDestination(destination.getId()) == null) { NavGraph parent = destination.getParent(); if (parent != null) { hierarchy.addFirst(new NavBackStackEntry(parent, finalArgs)); } destination = parent; } mBackStack.addAll(hierarchy); NavBackStackEntry newBackStackEntry = new NavBackStackEntry(newDest, newDest.addInDefaultArgs(finalArgs)); mBackStack.add(newBackStackEntry); } updateOnBackPressedCallbackEnabled(); if (popped || newDest != null) { dispatchOnDestinationChanged(); } }
Source:
public void testSuccessfullIdx() throws IOException { final List<Pass> list = new ArrayList<Pass>(2); list.add(new PsFake(true)); list.add(new PsFake(true)); final Opt<Identity> identity = new PsAll(list, 1).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(true) ); }

Target:
public void testSuccessfullIdx() throws Exception { final List<Pass> list = new ArrayList<Pass>(2); list.add(new PsFake(true)); list.add(new PsFake(true)); final Opt<Identity> identity = new PsAll(list, 1).enter(new RqFake()); MatcherAssert.assertThat( identity.has(), Matchers.is(true) ); }
Source:
public void testGet() { Path path = new Path("/path"); PathMetadata pathMeta1 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir1"), TEST_OWNER)); PathMetadata pathMeta2 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir2"), TEST_OWNER)); PathMetadata pathMeta3 = new PathMetadata( new S3AFileStatus(123, 456, new Path(path, "file1"), 8192, TEST_OWNER, "abc", "def")); List<PathMetadata> listing = Arrays.asList(pathMeta1, pathMeta2, pathMeta3); DirListingMetadata meta = new DirListingMetadata(path, listing, false); assertEquals(path, meta.getPath()); assertNotNull(meta.getListing()); assertFalse(meta.getListing().isEmpty()); assertTrue(meta.getListing().contains(pathMeta1)); assertTrue(meta.getListing().contains(pathMeta2)); assertTrue(meta.getListing().contains(pathMeta3)); assertFalse(meta.isAuthoritative()); assertEquals(pathMeta1, meta.get(pathMeta1.getFileStatus().getPath())); assertEquals(pathMeta2, meta.get(pathMeta2.getFileStatus().getPath())); assertEquals(pathMeta3, meta.get(pathMeta3.getFileStatus().getPath())); assertNull(meta.get(new Path(path, "notfound"))); }

Target:
public void testGet() { Path path = new Path("/path"); PathMetadata pathMeta1 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir1"), TEST_OWNER)); PathMetadata pathMeta2 = new PathMetadata( new S3AFileStatus(true, new Path(path, "dir2"), TEST_OWNER)); PathMetadata pathMeta3 = new PathMetadata( new S3AFileStatus(123, 456, new Path(path, "file1"), 8192, TEST_OWNER, TEST_ETAG, TEST_VERSION_ID)); List<PathMetadata> listing = Arrays.asList(pathMeta1, pathMeta2, pathMeta3); DirListingMetadata meta = new DirListingMetadata(path, listing, false); assertEquals(path, meta.getPath()); assertNotNull(meta.getListing()); assertFalse(meta.getListing().isEmpty()); assertTrue(meta.getListing().contains(pathMeta1)); assertTrue(meta.getListing().contains(pathMeta2)); assertTrue(meta.getListing().contains(pathMeta3)); assertFalse(meta.isAuthoritative()); assertEquals(pathMeta1, meta.get(pathMeta1.getFileStatus().getPath())); assertEquals(pathMeta2, meta.get(pathMeta2.getFileStatus().getPath())); assertEquals(pathMeta3, meta.get(pathMeta3.getFileStatus().getPath())); assertNull(meta.get(new Path(path, "notfound"))); }
Source:
public void testSyncDoSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); AccessResult result = accessor.doSet(_gZkClient, path, record, -1, AccessOption.PERSISTENT); Assert.assertEquals(result._retCode, RetCode.OK); Assert.assertEquals(result._pathCreated.size(), 3); Assert.assertTrue(result._pathCreated.contains(String.format("/%s/%s", _rootPath, "msg_0"))); Assert.assertTrue(result._pathCreated.contains(path)); Assert.assertTrue(_gZkClient.exists(String.format("/%s/%s", _rootPath, "msg_0"))); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "submsg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }

Target:
public void testSyncDoSet() { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String testName = className + "_" + methodName; System.out.println("START " + testName + " at " + new Date(System.currentTimeMillis())); String path = String.format("/%s/%s/%s", _rootPath, "msg_0", "submsg_0"); ZNRecord record = new ZNRecord("submsg_0"); ZkBaseDataAccessor<ZNRecord> accessor = new ZkBaseDataAccessor<ZNRecord>(_gZkClient); AccessResult result = accessor.doSet(path, record, -1, AccessOption.PERSISTENT); Assert.assertEquals(result._retCode, RetCode.OK); Assert.assertEquals(result._pathCreated.size(), 3); Assert.assertTrue(result._pathCreated.contains(String.format("/%s/%s", _rootPath, "msg_0"))); Assert.assertTrue(result._pathCreated.contains(path)); Assert.assertTrue(_gZkClient.exists(String.format("/%s/%s", _rootPath, "msg_0"))); ZNRecord getRecord = _gZkClient.readData(path); Assert.assertNotNull(getRecord); Assert.assertEquals(getRecord.getId(), "submsg_0"); System.out.println("END " + testName + " at " + new Date(System.currentTimeMillis())); }
Source:
protected <T extends Connection> void parseConnectionList(EClass conType, EList<T> connectionlist, String parentNodeName) throws XMLStreamException, TypeImportException { processChildren(parentNodeName, name -> { if (name.equals(LibraryElementTags.CONNECTION_ELEMENT)) { T connection = parseConnection(conType); if (null != connection) { connectionlist.add(connection); } proceedToEndElementNamed(LibraryElementTags.CONNECTION_ELEMENT); return true; } return false; }); }

Target:
protected <T extends Connection> void parseConnectionList(EClass conType, EList<T> connectionlist, String parentNodeName) throws XMLStreamException, TypeImportException { processChildren(parentNodeName, name -> { if (LibraryElementTags.CONNECTION_ELEMENT.equals(LibraryElementTags.CONNECTION_ELEMENT)) { T connection = parseConnection(conType); if (null != connection) { connectionlist.add(connection); } proceedToEndElementNamed(LibraryElementTags.CONNECTION_ELEMENT); return true; } return false; }); }
Source:
protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); serverURI.append((secure ? "ssl://" : "tcp://")); serverURI.append(host); serverURI.append(":"); serverURI.append(port); Path tmpDir = Paths.get(ConfigConstants.DEFAULT_USERDATA_FOLDER); try { if (!tmpDir.isAbsolute()) { throw new IOException("User path not absolute!"); } tmpDir = Files.createDirectories(tmpDir).resolve("mqtt").resolve(host); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }

Target:
protected MqttAsyncClient createAndConnectClient() throws MqttException, ConfigurationException { StringBuilder serverURI = new StringBuilder(); serverURI.append((secure ? "ssl://" : "tcp://")); serverURI.append(host); serverURI.append(":"); serverURI.append(port); Path tmpDir = Paths.get(ConfigConstants.getUserDataFolder()); try { tmpDir = Files.createDirectories(tmpDir.resolve("mqtt").resolve(host)); } catch (IOException e) { throw new MqttException(e); } MqttClientPersistence dataStore = new MqttDefaultFilePersistence(tmpDir.toString()); MqttAsyncClient _client; try { _client = new MqttAsyncClient(serverURI.toString(), clientId, dataStore); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } _client.setCallback(clientCallbacks); try { connectionToken = _client.connect(createMqttOptions(), null, connectionCallbacks); logger.info("Starting MQTT broker connection to '{}' with clientid and file store '{}'", host, getClientId(), tmpDir); } catch (org.eclipse.paho.client.mqttv3.MqttException e) { throw new MqttException(e); } return _client; }
Source:
private void addParametersToStartBlock(StatementList statementList) { if (statementList.parent().is(Tree.Kind.FUNCDEF)) { ParameterList parameterList = ((FunctionDef) statementList.parent()).parameters(); if (parameterList != null) { PythonCfgSimpleBlock parametersBlock = createSimpleBlock(start); parameterList.all().forEach(parameter -> { if (parameter.is(Tree.Kind.PARAMETER)) { parametersBlock.addElement(parameter); return; } addTupleParam((TupleParameter) parameter, parametersBlock); }); start = parametersBlock; } } }

Target:
private void addParametersToStartBlock(StatementList statementList) { if (statementList.parent().is(Tree.Kind.FUNCDEF)) { ParameterList parameterList = ((FunctionDef) statementList.parent()).parameters(); if (parameterList != null) { PythonCfgSimpleBlock parametersBlock = createSimpleBlock(start); addParameters(parameterList.all(), parametersBlock); start = parametersBlock; } } }
Source:
void execute() throws AzureBlobFileSystemException { int retryCount = 0; LOG.debug("First execution of REST operation - " + operationType); while (!executeHttpOperation(retryCount++)) { try { LOG.debug("Retrying REST operation " + operationType + ". RetryCount" + "=" + retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } }

Target:
void execute() throws AzureBlobFileSystemException { String latencyHeader = this.client.getAbfsPerfTracker().getClientLatency(); if (latencyHeader != null && !latencyHeader.isEmpty()) { AbfsHttpHeader httpHeader = new AbfsHttpHeader(HttpHeaderConfigurations.X_MS_ABFS_CLIENT_LATENCY, latencyHeader); requestHeaders.add(httpHeader); } int retryCount = 0; LOG.debug("First execution of REST operation - {}", operationType); while (!executeHttpOperation(retryCount++)) { try { LOG.debug("Retrying REST operation {}. RetryCount = {}", operationType, retryCount); Thread.sleep(client.getRetryPolicy().getRetryInterval(retryCount)); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } if (result.getStatusCode() >= HttpURLConnection.HTTP_BAD_REQUEST) { throw new AbfsRestOperationException(result.getStatusCode(), result.getStorageErrorCode(), result.getStorageErrorMessage(), null, result); } }
Source:
public void shouldCreateStandaloneClientWithZookeeper() { RatelClientFactory ratelStandaloneFactory = RatelStandaloneFactory.fromZookeeperServer(ZK_HOST); TestService testedService = ratelStandaloneFactory.getServiceProxy(TestService.class, null); then(testedService.hello()).isEqualTo("success"); }

Target:
public void shouldCreateStandaloneClientWithZookeeper() { RatelClientFactory ratelStandaloneFactory = RatelStandaloneFactory.fromZookeeperServer(ZK_HOST); TestService testedService = ratelStandaloneFactory.getServiceProxy(TestService.class); then(testedService.hello()).isEqualTo("success"); }
Source:
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] inBytes = EntityUtils.toByteArray(entity); TTransport input = new TMemoryInputTransport(Arrays.copyOfRange(inBytes, 4, inBytes.length)); TMemoryBuffer output = new TMemoryBuffer(inBytes.length); try { processor.process(inputProtoFactory.getProtocol(input), outputProtoFactory.getProtocol(output)); } catch (TException e) { LOGGER.warn("error processing frame, discarding: " + e.getMessage()); return; } if (output.length() == 0) { return; } byte[] outBytes = new byte[output.length() + 4]; ProtocolUtils.writeInt(output.length(), outBytes, 0); System.arraycopy(output.getArray(), 0, outBytes, 4, output.length()); response.setStatusLine(new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), 200, "OK")); response.setHeader("accept", "application/x-frugal"); response.setHeader("content-transfer-encoding", "base64"); response.setEntity(new ByteArrayEntity(outBytes)); } }

Target:
public void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException { if (!(request instanceof HttpEntityEnclosingRequest)) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase("BAD REQUEST"); return; } HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); byte[] inBytes = Base64.decodeBase64(EntityUtils.toByteArray(entity)); EntityUtils.consume(entity); if ((requestSizeLimit > 0) && (inBytes.length > requestSizeLimit)) { response.setStatusCode(HttpStatus.SC_REQUEST_TOO_LONG); response.setReasonPhrase("PAYLOAD TOO LARGE"); return; } TTransport input = new TMemoryInputTransport(Arrays.copyOfRange(inBytes, 4, inBytes.length)); TMemoryBuffer output = new TMemoryBuffer(inBytes.length); try { processor.process(inputProtoFactory.getProtocol(input), outputProtoFactory.getProtocol(output)); } catch (TException e) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setReasonPhrase("BAD REQUEST"); return; } Header payloadLimit = request.getFirstHeader(HttpHeaders.X_FRUGAL_PAYLOAD_LIMIT_HEADER); if (payloadLimit != null) { Integer limit = Integer.parseInt(payloadLimit.getValue()); if (output.getArray().length > limit) { response.setStatusCode(HttpStatus.SC_FORBIDDEN); response.setReasonPhrase("FORBIDDEN"); return; } } byte[] outBytes = new byte[output.length() + 4]; ProtocolUtils.writeInt(output.length(), outBytes, 0); System.arraycopy(output.getArray(), 0, outBytes, 4, output.length()); response.setStatusCode(HttpStatus.SC_OK); response.setReasonPhrase("OK"); response.setHeader(HttpHeaders.ACCEPT_HEADER, HttpHeaders.APPLICATION_X_FRUGAL_HEADER); response.setHeader(HttpHeaders.CONTENT_TRANSFER_ENCODING_HEADER, HttpHeaders.CONTENT_TRANSFER_ENCODING); response.setEntity(new StringEntity(Base64.encodeBase64String(outBytes), ContentType.create(HttpHeaders.APPLICATION_X_FRUGAL_HEADER, HttpHeaders.CONTENT_TYPE))); }
Source:
public void testAddClusterAzureProvider() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; System.setProperty(SystemPropertyKeys.CLOUD_ID, "TestID"); System.setProperty(SystemPropertyKeys.CLOUD_INFO_SOURCE, "TestURL"); System.setProperty(SystemPropertyKeys.CLOUD_PROVIDER, CloudProvider.AZURE.name()); System.setProperty(SystemPropertyKeys.CLOUD_INFO_PROCESSOR_NAME, "TestProcessor"); _clusterSetup.addCluster(clusterName, false,true); ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName); Assert.assertTrue(cloudConfigFromZk.isCloudEnabled()); Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID"); List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources(); Assert.assertNull(listUrlFromZk); Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName()); Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name()); System.clearProperty(SystemPropertyKeys.CLOUD_ID); System.clearProperty(SystemPropertyKeys.CLOUD_PROVIDER); System.clearProperty(SystemPropertyKeys.CLOUD_INFO_SOURCE); System.clearProperty(SystemPropertyKeys.CLOUD_INFO_PROCESSOR_NAME); }

Target:
public void testAddClusterAzureProvider() throws Exception { String className = TestHelper.getTestClassName(); String methodName = TestHelper.getTestMethodName(); String clusterName = className + "_" + methodName; CloudConfig.Builder cloudConfigInitBuilder = new CloudConfig.Builder(); cloudConfigInitBuilder.setCloudEnabled(true); cloudConfigInitBuilder.setCloudID("TestID"); cloudConfigInitBuilder.setCloudProvider(CloudProvider.AZURE); CloudConfig cloudConfigInit = cloudConfigInitBuilder.build(); _clusterSetup.addCluster(clusterName, false, cloudConfigInit); ConfigAccessor _configAccessor = new ConfigAccessor(_gZkClient); CloudConfig cloudConfigFromZk = _configAccessor.getCloudConfig(clusterName); Assert.assertTrue(cloudConfigFromZk.isCloudEnabled()); Assert.assertEquals(cloudConfigFromZk.getCloudID(), "TestID"); List<String> listUrlFromZk = cloudConfigFromZk.getCloudInfoSources(); Assert.assertNull(listUrlFromZk); Assert.assertNull(cloudConfigFromZk.getCloudInfoProcessorName()); Assert.assertEquals(cloudConfigFromZk.getCloudProvider(), CloudProvider.AZURE.name()); }
Source:
private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); if (toWrite.length() > 1024) { toWrite = "truncated: " + toWrite.substring(0, 1023); } if (toWrite.length() == 0) { toWrite += " "; } return AXml.textToXml(toWrite); }

Target:
private String convertCharacterProxyData(CharacterDataProxy dp) { String toWrite = dp.getValueAsString(); return AXml.textToXml(toWrite); }
Source:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { return new HashMap<>(); }

Target:
public Map<String, String> getEventHoverToolTipInfo(ITimeEvent event, long hoverTime) { return Collections.EMPTY_MAP; }
Source:
private void addContents(@NonNull Container container, final @NonNull Node node) { Computer c = node.toComputer(); if (c == null) { return; } String name; if (node instanceof Jenkins) { name = "master"; } else { name = "slave/" + node.getNodeName(); } container.add( new Content("nodes/" + name + "/RootCA.txt") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { out.println(getRootCA(node)); } catch (IOException e) { e.printStackTrace(out); } finally { out.flush(); } } } ); }

Target:
private void addContents(@NonNull Container container, final @NonNull Node node) { Computer c = node.toComputer(); if (c == null) { return; } String name; if (node instanceof Jenkins) { name = "master"; } else { name = "slave/" + node.getNodeName(); } container.add( new Content("nodes/" + name + "/RootCA.txt") { @Override public void writeTo(OutputStream os) throws IOException { PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(os, "utf-8"))); try { out.println(getRootCA(node)); } catch (IOException e) { e.printStackTrace(out); } catch (InterruptedException e) { e.printStackTrace(out); } finally { out.flush(); } } } ); }
Source:
public static double calculateGenotypeQualityFromPLs(final Genotype genotype) { Utils.nonNull(genotype); if (!genotype.hasPL()) { return Double.NaN; } else { int[] PLs = genotype.getPL(); if (PLs.length <= 1) { return Double.NaN; } else { int best = PLs[0], secondBest = Integer.MAX_VALUE; for (int i = 1; i < PLs.length; i++) { final int next = PLs[i]; if (next <= best) { secondBest = best; best = next; } else if (next < secondBest) { secondBest = next; } } return secondBest - best; } } }

Target:
public static double calculateGenotypeQualityFromPLs(final Genotype genotype) { Utils.nonNull(genotype); if (!genotype.hasPL()) { return Double.NaN; } else { final int GQ = GATKProtectedMathUtils.secondSmallestMinusSmallest(genotype.getPL(), -1); return GQ < 0 ? Double.NaN : (double) GQ; } }
Source:
public String getSystemProperty(String key) { SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertyAccess(key); } try { return Objects.toString(importedSystemProperties.get(key), null); } catch (NullPointerException e) { throw new MigrationException(ImportMigrationContextImpl.INVALID_NULL_SYS_PROPS, e); } }

Target:
public String getSystemProperty(String key) { final SecurityManager sm = System.getSecurityManager(); if (sm != null) { sm.checkPropertyAccess(key); } return Objects.toString(importedSystemProperties.get(key), null); }
Source:
static ByteAmount getContainerRam(int components, int containers) { final int componentsPerContainer = Math.max(components / containers, 1); return ByteAmount.fromMegabytes(COMPONENT_RAM_MB * (componentsPerContainer + 2)); }

Target:
static ByteAmount getContainerRam(int components, int containers) { final int componentsPerContainer = Math.max(components / containers, 1); return ByteAmount.fromMegabytes(COMPONENT_RAM_MB * componentsPerContainer + DEFAULT_RAM_PADDING_PER_CONTAINER); }
Source:
public boolean isTotalOrderCache(String cacheName) { if (!running) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); } return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); } return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); if (log.isTraceEnabled()) { log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); } return totalOrder; }

Target:
public boolean isTotalOrderCache(String cacheName) { if (!running) { log.tracef("isTotalOrderCache(%s) returning false because the local cache manager is not running", cacheName); return false; } LocalCacheStatus cacheStatus = runningCaches.get(cacheName); if (cacheStatus == null) { log.tracef("isTotalOrderCache(%s) returning false because the cache doesn't exist locally", cacheName); return false; } boolean totalOrder = cacheStatus.getJoinInfo().isTotalOrder(); log.tracef("isTotalOrderCache(%s) returning %s", cacheName, totalOrder); return totalOrder; }
Source:
public void testAllocateSimpleSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool()) { slotPool.registerTaskManager(taskManagerLocation.getResourceID()); SlotRequestId requestId = new SlotRequestId(); CompletableFuture<PhysicalSlot> future = requestNewAllocatedSlot(slotPool, requestId); assertFalse(future.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(timeout.toMilliseconds(), TimeUnit.MILLISECONDS); final SlotOffer slotOffer = new SlotOffer( slotRequest.getAllocationId(), 0, DEFAULT_TESTING_PROFILE); assertTrue(slotPool.offerSlot(taskManagerLocation, taskManagerGateway, slotOffer)); PhysicalSlot physicalSlot = future.get(1, TimeUnit.SECONDS); assertTrue(future.isDone()); assertEquals(taskManagerLocation, physicalSlot.getTaskManagerLocation()); assertEquals(slotRequest.getAllocationId(), physicalSlot.getAllocationId()); } }

Target:
public void testAllocateSimpleSlot() throws Exception { CompletableFuture<SlotRequest> slotRequestFuture = new CompletableFuture<>(); resourceManagerGateway.setRequestSlotConsumer(slotRequestFuture::complete); try (SlotPoolImpl slotPool = createAndSetUpSlotPool(resourceManagerGateway)) { final SlotRequestId requestId = new SlotRequestId(); final CompletableFuture<PhysicalSlot> future = requestNewAllocatedSlot(slotPool, requestId); assertFalse(future.isDone()); final SlotRequest slotRequest = slotRequestFuture.get(TIMEOUT.toMilliseconds(), TimeUnit.MILLISECONDS); assertTrue(registerAndOfferSlot(taskManagerLocation, slotPool, slotRequest.getAllocationId())); final PhysicalSlot physicalSlot = future.get(1, TimeUnit.SECONDS); assertTrue(future.isDone()); assertEquals(taskManagerLocation, physicalSlot.getTaskManagerLocation()); assertEquals(slotRequest.getAllocationId(), physicalSlot.getAllocationId()); } }
Source:
protected DeviceAnonymized(UUID id, UserAnonymized userAnonymized, int deviceId) { super(id); Objects.requireNonNull(userAnonymized); this.userAnonymized = userAnonymized; this.deviceId = deviceId; }

Target:
protected DeviceAnonymized(UUID id, UserAnonymized userAnonymized, int deviceId) { super(id); this.userAnonymized = Objects.requireNonNull(userAnonymized); this.deviceId = deviceId; }
Source:
int getSchemaVersion() { int version; try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { String selectVersionSql = "SELECT \"id\" FROM \"Version\""; ResultSet resultSet = statement.executeQuery(selectVersionSql); if (resultSet.next()) { version = resultSet.getInt("id"); } else { throw new SQLException("Expected non-empty result set"); } } } catch (SQLException e) { throw new RuntimeException(e); } return version; }

Target:
int getSchemaVersion() { int version; try (Connection connection = dataSource.getConnection()) { try (Statement statement = connection.createStatement()) { String selectVersionSql = "SELECT \"id\" FROM \"Version\""; try (ResultSet resultSet = statement.executeQuery(selectVersionSql)) { if (resultSet.next()) { version = resultSet.getInt("id"); } else { throw new SQLException("Expected non-empty result set"); } } } } catch (SQLException e) { throw new UncheckedSqlException(e); } return version; }
Source:
static Boolean isCookiesAuthEnabled(Map<String, String> attributes) { String val = attributes.get(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE); return val == null ? null : Boolean.parseBoolean(val); }

Target:
static @Nullable Boolean isCookiesAuthEnabled(Map<String, String> attributes) { String val = attributes.get(SECURE_SERVER_COOKIES_AUTH_ENABLED_ATTRIBUTE); return val == null ? null : Boolean.parseBoolean(val); }
Source:
private ValidationResult validateRequiredNetworksAvailable(VDS vds, VM vm, List<VmNetworkInterface> vmNICs, Network displayNetwork, Map<String, Network> networksByName, List<String> hostNetworks, VdsNetworkInterface displayNic) { List<String> missingIfs = new ArrayList<>(); boolean onlyRequiredNetworks = Config.<Boolean> getValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : vmNICs) { boolean found = false; boolean skipNetworkExistenceCheckForVnicPassthrough = vmIf.isPassthrough(); if (vmIf.getNetworkName() == null) { found = true; } else { for (String networkName : hostNetworks) { if (skipNetworkExistenceCheckForVnicPassthrough || !networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), networkName)) { found = true; break; } } } if (!found) { missingIfs.add(vmIf.getNetworkName()); } Network network = networksByName.get(vmIf.getNetworkName()); if (network.isExternal()) { checkExternalNetworkConnection(network, hostNetworks).ifPresent(missingIfs::add); } } if (!missingIfs.isEmpty()) { String nics = StringUtils.join(missingIfs, ", "); log.warn("host is missing networks required by VM nics {}", vds.getName(), nics); return new ValidationResult(EngineMessage.VAR__DETAIL__NETWORK_MISSING, String.format("$networkNames %1$s", nics)); } return validateDisplayNetworkAvailability(vds, onlyRequiredNetworks, displayNic, displayNetwork); }

Target:
private ValidationResult validateRequiredNetworksAvailable(VDS vds, VM vm, List<VmNetworkInterface> vmNICs, Network displayNetwork, Map<String, Network> networksByName, List<String> hostNetworks, VdsNetworkInterface displayNic) { List<String> missingIfs = new ArrayList<>(); boolean onlyRequiredNetworks = Config.<Boolean> getValue(ConfigValues.OnlyRequiredNetworksMandatoryForVdsSelection); for (final VmNetworkInterface vmIf : vmNICs) { boolean found = false; boolean skipNetworkExistenceCheckForVnicPassthrough = vmIf.isPassthrough(); if (vmIf.getNetworkName() == null) { found = true; } else { for (String networkName : hostNetworks) { if (skipNetworkExistenceCheckForVnicPassthrough || !networkRequiredOnVds(vmIf, networksByName, onlyRequiredNetworks) || StringUtils.equals(vmIf.getNetworkName(), networkName)) { found = true; break; } } Network network = networksByName.get(vmIf.getNetworkName()); if (network.isExternal()) { findPhysicalNetworkNotConnectedAndLinkedTo(network, hostNetworks).ifPresent(missingIfs::add); } } if (!found) { missingIfs.add(vmIf.getNetworkName()); } } if (!missingIfs.isEmpty()) { String nics = StringUtils.join(missingIfs, ", "); log.warn("host is missing networks required by VM nics {}", vds.getName(), nics); return new ValidationResult(EngineMessage.VAR__DETAIL__NETWORK_MISSING, String.format("$networkNames %1$s", nics)); } return validateDisplayNetworkAvailability(vds, onlyRequiredNetworks, displayNic, displayNetwork); }
Source:
public synchronized void deploy(String verticle, Vertx vertx, DeploymentOptions options, Handler<AsyncResult<String>> completionHandler) { if (manager == null) { manager = newInstance(); } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classloader); Method method = manager.getClass().getMethod("deploy", String.class, Vertx.class, DeploymentOptions.class, Handler.class); method.invoke(manager, verticle, vertx, options, completionHandler); } catch (Exception e) { log.error("Failed to deploy verticle " + verticle, e); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } }

Target:
public synchronized void deploy(String verticle, Vertx vertx, DeploymentOptions options, Handler<AsyncResult<String>> completionHandler) { if (manager == null) { manager = newInstance(); } final ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader(); try { Thread.currentThread().setContextClassLoader(classloader); Method method = manager.getClass().getMethod("deploy", String.class, Vertx.class, DeploymentOptions.class, Handler.class); method.invoke(manager, verticle, vertx, options, completionHandler); } catch (InvocationTargetException e) { log.error("Failed to deploy verticle " + verticle, e.getCause()); } catch (Exception e) { log.error("Failed to deploy verticle " + verticle, e); } finally { Thread.currentThread().setContextClassLoader(originalClassLoader); } }
Source:
public long getEngineSessionSeqId(String sessionId) { return sessionInfoMap.containsKey(sessionId) ? (Long) sessionInfoMap.get(sessionId).contentOfSession.get(ENGINE_SESSION_SEQ_ID) : -1; }

Target:
public long getEngineSessionSeqId(String sessionId) { if (!sessionInfoMap.containsKey(sessionId)) { throw new RuntimeException("Session not found for sessionId " + sessionId); } return (Long) sessionInfoMap.get(sessionId).contentOfSession.get(ENGINE_SESSION_SEQ_ID); }
Source:
private byte decodeRecordToJson(GenericRecord record) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, outputStream); writer.write(record, jsonEncoder); jsonEncoder.flush(); outputStream.close(); return outputStream.toByteArray(); }

Target:
private byte decodeRecordToJson(GenericRecord record) throws IOException { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); JsonEncoder jsonEncoder = EncoderFactory.get().jsonEncoder(schema, outputStream); writer.write(record, jsonEncoder); jsonEncoder.flush(); return outputStream.toByteArray(); }
Source:
private static boolean isDeckPackage(String filename) { return filename != null && (filename.toLowerCase().endsWith(".apkg") || filename.toLowerCase().endsWith(".apkg.zip")) && !filename.equals("collection.apkg"); }

Target:
private static boolean isDeckPackage(String filename) { return filename != null && (filename.toLowerCase().endsWith(".apkg") || filename.toLowerCase().endsWith(".apkg.zip")) && !(filename.equals("collection.apkg") || filename.equals("collection.apkg.zip")); }
Source:
public void onNavigationDrawerItemSelected(int position) { if (position != menu_position) { startActivity(intent_list.get(position)); Set<String> categories = getIntent().getCategories(); getIntent().getAction(); if(categories == null || ! (categories.contains("android.intent.category.LAUNCHER") || getMenuName().equalsIgnoreCase(Home.menu_name))){ finish(); } } }

Target:
public void onNavigationDrawerItemSelected(int position) { if (position != menu_position) { startActivity(intent_list.get(position)); if (!getMenuName().equalsIgnoreCase(Home.menu_name)) { finish(); } } }
Source:
public void inspectAddresses(CorfuPayloadMsg<InspectAddressesRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { log.trace("inspectAddresses: {}", msg.getPayload().getAddresses()); InspectAddressesResponse inspectResponse = new InspectAddressesResponse(); try { for (long address : msg.getPayload().getAddresses()) { if (!streamLog.contains(address)) { inspectResponse.add(address); } } r.sendResponse(ctx, msg, CorfuMsgType.INSPECT_ADDRESSES_RESPONSE.payloadMsg(inspectResponse)); } catch (TrimmedException te) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); } catch (DataCorruptionException dce) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.msg()); } }

Target:
public void inspectAddresses( CorfuPayloadMsg<InspectAddressesRequest> msg, ChannelHandlerContext ctx, IServerRouter r) { List<Long> addresses = msg.getPayload().getAddresses(); log.trace("inspectAddresses: {}", addresses); InspectAddressesResponse inspectResponse = new InspectAddressesResponse(); for (long address : addresses) { try { if (!streamLog.contains(address)) { inspectResponse.add(address); } } catch (TrimmedException te) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_TRIMMED.msg()); return; } catch (DataCorruptionException dce) { r.sendResponse(ctx, msg, CorfuMsgType.ERROR_DATA_CORRUPTION.payloadMsg(address)); return; } } r.sendResponse(ctx, msg, CorfuMsgType.INSPECT_ADDRESSES_RESPONSE.payloadMsg(inspectResponse)); }
Source:
public boolean provides(IDiagramElementEditPart editPart) { boolean provides = false; if (editPart instanceof GraphicalEditPart || editPart instanceof AbstractConnectionEditPart) { View view = (View) editPart.getModel(); if (view != null) { if (view instanceof Edge || view.isSetElement()) { EditDomain ed = editPart.getViewer().getEditDomain(); if (ed instanceof DiagramEditDomain) { EObject model = view.getElement(); provides = model instanceof DNode || model instanceof DDiagramElementContainer; } } } } return provides; }

Target:
public boolean provides(IDiagramElementEditPart editPart) { if (editPart instanceof GraphicalEditPart || editPart instanceof AbstractConnectionEditPart) { Optional<View> view = Optional.ofNullable((View) editPart.getModel()); return view.filter(View::isSetElement).map(View::getElement).filter(model -> model instanceof DNode || model instanceof DDiagramElementContainer).isPresent(); } return false; }
Source:
private static Timeline createTimeline( final Storage storage, final UUID id, final int order, final String topic, final String eventType, final Date createdAt, final Date switchedAt, final Date cleanupAt, final Timeline.StoragePosition latestPosition) { final Timeline timeline = new Timeline(); timeline.setId(id); timeline.setStorage(storage); timeline.setOrder(order); timeline.setTopic(topic); timeline.setEventType(eventType); timeline.setCreatedAt(createdAt); timeline.setSwitchedAt(switchedAt); timeline.setCleanupAt(cleanupAt); timeline.setLatestPosition(latestPosition); return timeline; }

Target:
private static Timeline createTimeline( final Storage storage, final UUID id, final int order, final String topic, final String eventType, final Date createdAt, final Date switchedAt, final Date cleanupAt, final Timeline.StoragePosition latestPosition) { final Timeline timeline = new Timeline(eventType, order, storage, topic, createdAt); timeline.setId(id); timeline.setSwitchedAt(switchedAt); timeline.setCleanupAt(cleanupAt); timeline.setLatestPosition(latestPosition); return timeline; }
Source:
public String getMessage() { StringBuilder builder; if (message != null) { builder = new StringBuilder().append(message); } else { builder = new StringBuilder().append(error); } if (!elements.isEmpty()) { builder.append(" ").append(elements); } return builder.toString(); }

Target:
public String getMessage() { StringBuilder builder = new StringBuilder().append(super.getMessage()); if (!elements.isEmpty()) { builder.append(" ").append(elements); } return builder.toString(); }
Source:
public int getItemCount() { if (currentPath == null) return 0; else return entries.size(); }

Target:
public int getItemCount() { if (currentPath == null) { return 0; } else { return entries.size(); } }
Source:
public Map<StreamId, OrcDataSourceInput> getInputs(OrcDataSource orcDataSource, StripeId stripeId, Map<StreamId, DiskRange> diskRanges) throws IOException { ImmutableMap.Builder<StreamId, OrcDataSourceInput> inputsBuilder = ImmutableMap.builder(); ImmutableMap.Builder<StreamId, DiskRange> diskRangesBuilder = ImmutableMap.builder(); for (Entry<StreamId, DiskRange> entry : diskRanges.entrySet()) { if (isCachedStream(entry.getKey().getStreamKind())) { Slice streamSlice = stripeStreamCache.getIfPresent(new StripeStreamId(stripeId, entry.getKey())); if (streamSlice != null) { inputsBuilder.put(entry.getKey(), new OrcDataSourceInput(new BasicSliceInput(streamSlice), streamSlice.length())); } else { diskRangesBuilder.put(entry); } } else { diskRangesBuilder.put(entry); } } Map<StreamId, OrcDataSourceInput> notCachedInputs = delegate.getInputs(orcDataSource, stripeId, diskRangesBuilder.build()); for (Entry<StreamId, OrcDataSourceInput> entry : notCachedInputs.entrySet()) { if (isCachedStream(entry.getKey().getStreamKind())) { Slice streamSlice = entry.getValue().getInput().readSlice(toIntExact(entry.getValue().getInput().length())); stripeStreamCache.put(new StripeStreamId(stripeId, entry.getKey()), streamSlice); inputsBuilder.put(entry.getKey(), new OrcDataSourceInput(new BasicSliceInput(streamSlice), toIntExact(streamSlice.getRetainedSize()))); } else { inputsBuilder.put(entry.getKey(), entry.getValue()); } } return inputsBuilder.build(); }

Target:
public Map<StreamId, OrcDataSourceInput> getInputs(OrcDataSource orcDataSource, StripeId stripeId, Map<StreamId, DiskRange> diskRanges) throws IOException { ImmutableMap.Builder<StreamId, OrcDataSourceInput> inputsBuilder = ImmutableMap.builder(); ImmutableMap.Builder<StreamId, DiskRange> uncachedDiskRangesBuilder = ImmutableMap.builder(); for (Entry<StreamId, DiskRange> entry : diskRanges.entrySet()) { if (isCachedStream(entry.getKey().getStreamKind())) { Slice streamSlice = stripeStreamCache.getIfPresent(new StripeStreamId(stripeId, entry.getKey())); if (streamSlice != null) { inputsBuilder.put(entry.getKey(), new OrcDataSourceInput(new BasicSliceInput(streamSlice), streamSlice.length())); } else { uncachedDiskRangesBuilder.put(entry); } } else { uncachedDiskRangesBuilder.put(entry); } } Map<StreamId, OrcDataSourceInput> uncachedInputs = delegate.getInputs(orcDataSource, stripeId, uncachedDiskRangesBuilder.build()); for (Entry<StreamId, OrcDataSourceInput> entry : uncachedInputs.entrySet()) { if (isCachedStream(entry.getKey().getStreamKind())) { Slice streamSlice = entry.getValue().getInput().readSlice(toIntExact(entry.getValue().getInput().length())); stripeStreamCache.put(new StripeStreamId(stripeId, entry.getKey()), streamSlice); inputsBuilder.put(entry.getKey(), new OrcDataSourceInput(new BasicSliceInput(streamSlice), toIntExact(streamSlice.getRetainedSize()))); } else { inputsBuilder.put(entry.getKey(), entry.getValue()); } } return inputsBuilder.build(); }
Source:
private String getMemberRelPath(Repository repo, IResource member) { String repoWorkDir = repo.getWorkDir().toString(); if (!"/".equals(File.separator)) { repoWorkDir = repoWorkDir.replace(File.separatorChar, '/'); } String memberRelPath = member.getLocation().toString(); memberRelPath = memberRelPath.replace(repoWorkDir, ""); if (memberRelPath.startsWith("/")) { memberRelPath = memberRelPath.substring(1); } return memberRelPath; }

Target:
private String getMemberRelPath(Repository repo, IResource member) { String repoWorkDir = repo.getWorkDir().toString(); if (!"/".equals(File.separator)) { repoWorkDir = repoWorkDir.replace(File.separatorChar, '/'); } String memberRelPath = member.getLocation().toString(); memberRelPath = memberRelPath.replace(repoWorkDir, ""); if (memberRelPath.startsWith("/")) memberRelPath = memberRelPath.substring(1); return memberRelPath; }
Source:
public void decodeFromJsonTo(PreparedStatement toStatement, int toIndex, JsonNode fromValue) throws SQLException { try { final Instant epoch = PARSER.parse(fromValue.asText()); Timestamp sqlTimestamp = new Timestamp(epoch.getEpochSecond() * 1000L); sqlTimestamp.setNanos(epoch.getNano()); toStatement.setTimestamp(toIndex, sqlTimestamp); } catch (final DateTimeParseException e) { long now = System.currentTimeMillis(); String sample = format(now / 1000, (int)((now % 1000)*1000000)); throw new ConfigException("Invalid timestamp with time zone pattern: " + fromValue + "." + " The pattern must be 'yyyy-MM-ddTHH:mm:ss.SSSSSSZ'." + " e.g. \"" + sample + "\" or \"" + sample.replace("Z", "+0000") + "\""); } }

Target:
public void decodeFromJsonTo(PreparedStatement toStatement, int toIndex, JsonNode fromValue) throws SQLException { try { final Instant epoch = PARSER.parse(fromValue.asText()); final Timestamp sqlTimestamp = Timestamp.from(epoch); sqlTimestamp.setNanos(epoch.getNano()); toStatement.setTimestamp(toIndex, sqlTimestamp); } catch (final DateTimeParseException e) { long now = System.currentTimeMillis(); String sample = format(now / 1000, (int)((now % 1000)*1000000)); throw new ConfigException("Invalid timestamp with time zone pattern: " + fromValue + "." + " The pattern must be 'yyyy-MM-ddTHH:mm:ss.SSSSSSZ'." + " e.g. \"" + sample + "\" or \"" + sample.replace("Z", "+0000") + "\""); } }
Source:
private OCFile getCurrentFolder(){ OCFile file = mFile; if (file != null) { if (file.isFolder()) { return file; } else if (getStorageManager() != null) { String parentPath = file.getRemotePath().substring(0, file.getRemotePath().lastIndexOf(file.getFileName())); return getStorageManager().getFileByPath(parentPath); } } return null; }

Target:
private OCFile getCurrentFolder(){ OCFile file = mFile; if (file != null) { if (file.isFolder()) { return file; } else if (getStorageManager() != null) { return getStorageManager().getFileByPath(file.getParentRemotePath()); } } return null; }
Source:
public View getTopContainer(final View view) { View topView = null; EObject container; if (view != null) { container = view.eContainer(); if (isStereotypeCompartment(container) || isStereotypeBrace(container) || isStereotypeLabel(container)) { container = container.eContainer(); } if (container instanceof View) { topView = (View) container; } } return topView; }

Target:
public View getTopContainer(final View view) { View topView = null; if (view != null) { EObject container = view.eContainer(); if (isStereotypeCompartment(container) || isStereotypeBrace(container) || isStereotypeLabel(container)) { container = container.eContainer(); } if (container instanceof View) { topView = (View) container; } } return topView; }
Source:
public DeferredItem(Rectangle bounds, RGBAColor backgroundColor, RGBAColor foregroundColor, int alpha, int lineWidth) { fBounds = bounds; fLineWidth = lineWidth; if (backgroundColor == null) { fBgColor = OPAQUE; } else if (backgroundColor.getAlpha() != alpha) { fBgColor = new RGBAColor(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), alpha); } else { fBgColor = backgroundColor; } fFgColor = foregroundColor; }

Target:
public DeferredItem(Rectangle bounds, RGBAColor backgroundColor, RGBAColor foregroundColor, int alpha, int lineWidth) { fBounds = bounds; fLineWidth = lineWidth; if (backgroundColor.getAlpha() != alpha) { fBgColor = new RGBAColor(backgroundColor.getRed(), backgroundColor.getGreen(), backgroundColor.getBlue(), alpha); } else { fBgColor = backgroundColor; } fFgColor = foregroundColor; }