auphong2707/dl4se-code-review-dataset huggingface dataset:
Source:
protected void executeQueryCommand() { GlusterGeoRepDao geoRepDao = getGeoRepDao(); List<GlusterGeoRepSession> geoRepSessions = geoRepDao.getGeoRepSessions(getParameters().getId()); if (geoRepSessions != null) { for (GlusterGeoRepSession currentSession : geoRepSessions) { ArrayList<GlusterGeoRepSessionDetails> currentSessionDetails = (ArrayList<GlusterGeoRepSessionDetails>) geoRepDao.getGeoRepSessionDetails(currentSession.getId()); currentSession.setSessionDetails(currentSessionDetails); if (currentSession.getSessionDetails() != null) { for (GlusterGeoRepSessionDetails currentDetail : currentSession.getSessionDetails()) { GlusterBrickEntity currentBrick = getGlusterBrickDao().getById(currentDetail.getMasterBrickId()); if (currentBrick != null) { currentDetail.setMasterBrickNode(currentBrick.getServerName()); } } } } } getQueryReturnValue().setReturnValue(geoRepSessions); }

Target:
protected void executeQueryCommand() { GlusterGeoRepDao geoRepDao = getGeoRepDao(); List<GlusterGeoRepSession> geoRepSessions = geoRepDao.getGeoRepSessions(getParameters().getId()); if (geoRepSessions != null) { for (GlusterGeoRepSession currentSession : geoRepSessions) { List<GlusterGeoRepSessionDetails> geoRepSessionDetails = geoRepDao.getGeoRepSessionDetails(currentSession.getId()); if(geoRepSessionDetails == null) { continue; } ArrayList<GlusterGeoRepSessionDetails> currentSessionDetails = (ArrayList<GlusterGeoRepSessionDetails>) geoRepSessionDetails; currentSession.setSessionDetails(currentSessionDetails); if (currentSession.getSessionDetails() != null) { for (GlusterGeoRepSessionDetails currentDetail : currentSession.getSessionDetails()) { GlusterBrickEntity currentBrick = getGlusterBrickDao().getById(currentDetail.getMasterBrickId()); if (currentBrick != null) { currentDetail.setMasterBrickNode(currentBrick.getServerName()); } } } } } getQueryReturnValue().setReturnValue(geoRepSessions); }
Source:
public boolean visitMethod(UMethod node) { super.visitMethod(node); return !"onResume".equalsIgnoreCase(node.getName()); }

Target:
public boolean visitMethod(UMethod node) { super.visitMethod(node); return !"onResume".equalsIgnoreCase(node.getName()) || node.getReturnType() != PsiType.VOID || node.getUastParameters().size() != 0 || !isPublicOrProtected(node); }
Source:
public EDBObject getObject() { Map<String, Object> data = new HashMap<String, Object>(); for (KeyValuePair kvp : values) { data.put(kvp.getKey(), kvp.getValue()); } String s = (String) data.get("@isDeleted"); if (s != null) { data.put("@isDeleted", s.equals("true")); } return new EDBObject(uid, timestamp, data); }

Target:
public EDBObject getObject() { Map<String, Object> data = new HashMap<String, Object>(); for (JPAEntry kvp : entries) { data.put(kvp.getKey(), kvp.getValue()); } String s = (String) data.get("isDeleted"); if (s != null) { data.put("isDeleted", s.equals("true")); } EDBObject object = new EDBObject(oid, data); object.updateTimestamp(timestamp); return object; }
Source:
private DolphinContext createContext() { try{ return new DolphinContext(new DolphinPlatformConfiguration(), new DolphinSessionProvider() { @Override public DolphinSession getCurrentDolphinSession() { return null; } }, new ContainerManagerMock(), new ControllerRepository(classpathScanner), new DefaultOpenDolphinFactory(), new DestroyCallbackMock(), new DestroyCallbackMock()); }catch(ControllerValidationException cve){ return null; } }

Target:
private DolphinContext createContext() throws ControllerValidationException { return new DolphinContext(new DolphinPlatformConfiguration(), new DolphinSessionProvider() { @Override public DolphinSession getCurrentDolphinSession() { return null; } }, new ContainerManagerMock(), new ControllerRepository(classpathScanner), new DefaultOpenDolphinFactory(), new DestroyCallbackMock(), new DestroyCallbackMock()); }
Source:
private void deleteEnumerationLiteralClassifierChanges(ReferenceChange referenceChange) { if (isEnumerationLiteralClassifierChange(referenceChange)) { EcoreUtil.delete(referenceChange); } }

Target:
private void deleteEnumerationLiteralClassifierChanges(ReferenceChange referenceChange) { if (isEnumerationLiteralClassifierChange(referenceChange)) { delete(referenceChange); } }
Source:
public static Trace createTrace(Optional<Boolean> isObservable, String traceId) { validateId(traceId, "traceId must be non-empty: %s"); boolean observable = isObservable.orElse(sampler.sample()); return new Trace(observable, traceId); }

Target:
private static Trace createTrace(Optional<Boolean> isObservable, String traceId) { validateId(traceId, "traceId must be non-empty: %s"); boolean observable = isObservable.orElse(sampler.sample()); return new Trace(observable, traceId); }
Source:
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; } else if (savedRequest instanceof DefaultSavedRequest) { DefaultSavedRequest defaultSavedRequest = (DefaultSavedRequest) savedRequest; return defaultSavedRequest.doesRequestMatch(request, this.portResolver); } else { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } }

Target:
private boolean matchesSavedRequest(HttpServletRequest request, SavedRequest savedRequest) { if (savedRequest == null) { return false; } else { String currentUrl = UrlUtils.buildFullRequestUrl(request); return savedRequest.getRedirectUrl().equals(currentUrl); } }
Source:
public NetworkQoSCommandBase(NetworkQoSParametersBase parameters) { super(parameters); setStoragePoolId(parameters.getNetworkQoS().getStoragePoolId()); addCustomValue("NetworkQoSName", parameters.getNetworkQoS().getName()); getParameters().setShouldBeLogged(true); }

Target:
public NetworkQoSCommandBase(NetworkQoSParametersBase parameters) { super(parameters); if (getNetworkQoS() != null) { setStoragePoolId(getNetworkQoS().getStoragePoolId()); addCustomValue("NetworkQoSName", getNetworkQoS().getName()); } getParameters().setShouldBeLogged(true); addCanDoActionMessage(VdcBllMessages.VAR__ACTION__ADD); }
Source:
public ResultValidator<T> expectEvents(EventMessage... expectedEvents) { this.expectEvents((Object[]) (Stream.of(expectedEvents).map(Message::getPayload).toArray())); Iterator<EventMessage<?>> iterator = publishedEvents.iterator(); for (EventMessage expectedEvent : expectedEvents) { EventMessage actualEvent = iterator.next(); if (!verifyMetaDataEquality(expectedEvent.getPayloadType(), expectedEvent.getMetaData(), actualEvent.getMetaData())) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } } return this; }

Target:
public ResultValidator<T> expectEvents(EventMessage... expectedEvents) { this.expectEvents(Stream.of(expectedEvents).map(Message::getPayload).toArray()); Iterator<EventMessage<?>> iterator = publishedEvents.iterator(); for (EventMessage expectedEvent : expectedEvents) { EventMessage actualEvent = iterator.next(); if (!verifyMetaDataEquality(expectedEvent.getPayloadType(), expectedEvent.getMetaData(), actualEvent.getMetaData())) { reporter.reportWrongEvent(publishedEvents, Arrays.asList(expectedEvents), actualException); } } return this; }
Source:
protected void parseTickerFromJsonObject(int requestId, JSONObject jsonObject, Ticker ticker, CheckerInfo checkerInfo) throws Exception { ticker.bid = parsePrice(jsonObject.getJSONObject("message").getDouble("bid")); ticker.ask = parsePrice(jsonObject.getJSONObject("message").getDouble("ask")); ticker.vol = jsonObject.getJSONObject("message").getDouble("coinvolume") / 100000000; ticker.high = parsePrice(jsonObject.getJSONObject("message").getDouble("high")); ticker.low = parsePrice(jsonObject.getJSONObject("message").getDouble("low")); ticker.last = parsePrice(jsonObject.getJSONObject("message").getDouble("lastPrice")); }

Target:
protected void parseTickerFromJsonObject(int requestId, JSONObject jsonObject, Ticker ticker, CheckerInfo checkerInfo) throws Exception { final JSONObject messageJsonObject = jsonObject.getJSONObject("message"); ticker.bid = parsePrice(messageJsonObject.getDouble("bid")); ticker.ask = parsePrice(messageJsonObject.getDouble("ask")); ticker.vol = messageJsonObject.getDouble("coinvolume") / 100000000; ticker.high = parsePrice(messageJsonObject.getDouble("high")); ticker.low = parsePrice(messageJsonObject.getDouble("low")); ticker.last = parsePrice(messageJsonObject.getDouble("lastPrice")); }
Source:
public Day deserialize(Object val) { Day date = null; try { if (val instanceof String) { try { date = new Day(new Timestamp(FORMATTER.parse((String) val).getTime())); } catch (ParseException pe) { date = new Day(new Timestamp(ISO_FORMATTER.parse((String) val).getTime())); } } date = new Day(FORMATTER.parse(FORMATTER.format(val))); } catch (ParseException e) { throw new IllegalArgumentException("String must be formatted as " + FORMAT); } return date; }

Target:
public Day deserialize(Object val) { Day date = null; try { if (val instanceof String) { date = new Day(FORMATTER.parse(FORMATTER.format(TimeGrainFormatter.formatDateString(FORMATTER, (String) val)))); } else { date = new Day(FORMATTER.parse(FORMATTER.format(val))); } } catch (ParseException e) { throw new IllegalArgumentException("String must be formatted as " + FORMAT + " or " + TimeGrainFormatter.ISO_FORMAT); } return date; }
Source:
public static IdeDto asDto(Ide ide) { IdeDto ideDto = newDto(IdeDto.class); final OnAppClosed onAppClosed = ide.getOnAppClosed(); final OnAppLoaded onAppLoaded = ide.getOnAppLoaded(); final OnProjectsLoaded onProjectsLoaded = ide.getOnProjectsLoaded(); if (onAppClosed != null) { ideDto.withOnAppClosed(newDto(OnAppClosedDto.class).withActions(asDto(onAppClosed.getActions()))); } if (onAppLoaded != null) { ideDto.withOnAppLoaded(newDto(OnAppLoadedDto.class).withActions(asDto(onAppLoaded.getActions()))); } if (onProjectsLoaded != null) { ideDto.withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(asDto(onProjectsLoaded.getActions()))); } return ideDto; }

Target:
public static IdeDto asDto(Ide ide) { final IdeDto ideDto = newDto(IdeDto.class); final OnAppClosed onAppClosed = ide.getOnAppClosed(); final OnAppLoaded onAppLoaded = ide.getOnAppLoaded(); final OnProjectsLoaded onProjectsLoaded = ide.getOnProjectsLoaded(); if (onAppClosed != null) { ideDto.withOnAppClosed(newDto(OnAppClosedDto.class).withActions(asDto(onAppClosed.getActions()))); } if (onAppLoaded != null) { ideDto.withOnAppLoaded(newDto(OnAppLoadedDto.class).withActions(asDto(onAppLoaded.getActions()))); } if (onProjectsLoaded != null) { ideDto.withOnProjectsLoaded(newDto(OnProjectsLoadedDto.class).withActions(asDto(onProjectsLoaded.getActions()))); } return ideDto; }
Source:
public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(KeyVaultKey key) { builder.key(key); if (key == null) { throw logger.logExceptionAsError(new IllegalStateException( "Key is required to create key encryption key async client")); } if (key.getKey() == null) { throw logger.logExceptionAsError(new IllegalStateException( "Json Web key is required to create key encryption key async client")); } CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null ? builder.getServiceVersion() : CryptographyServiceVersion.getLatest(); if (builder.getPipeline() != null) { return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key, builder.getPipeline(), serviceVersion))); } if (builder.getCredential() == null) { throw logger.logExceptionAsError(new IllegalStateException( "Key Vault credentials are required to build the key encryption key async client")); } HttpPipeline pipeline = builder.setupPipeline(); return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key, pipeline, serviceVersion))); }

Target:
public Mono<? extends AsyncKeyEncryptionKey> buildAsyncKeyEncryptionKey(KeyVaultKey key) { builder.key(key); if (key == null) { throw logger.logExceptionAsError(new IllegalStateException( "Key Vault Key parameter cannot be null and is required to create key encryption key async client.")); } if (key.getKey() == null) { throw logger.logExceptionAsError(new IllegalStateException( "Json Web key value on the Key Vault Key object cannot be null and is required to create key encryption key async client.")); } CryptographyServiceVersion serviceVersion = builder.getServiceVersion() != null ? builder.getServiceVersion() : CryptographyServiceVersion.getLatest(); if (builder.getPipeline() != null) { return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key, builder.getPipeline(), serviceVersion))); } if (builder.getCredential() == null) { throw logger.logExceptionAsError(new IllegalStateException( "Key Vault credentials cannot be null and are required to build the key encryption key async client")); } HttpPipeline pipeline = builder.setupPipeline(); return Mono.defer(() -> Mono.just(new KeyEncryptionKeyAsyncClient(key, pipeline, serviceVersion))); }
Source:
public void updateChart(@NonNull Set<@NonNull Integer> quarks) { cancelUpdate(); resetData(); fQuarks.addAll(quarks); updateContent(); }

Target:
public void updateChart(@NonNull Set<@NonNull Integer> quarks) { cancelUpdate(); resetData(); fQuarks = quarks; updateContent(); }
Source:
private String getMigrationNetworkIp() { if (!FeatureSupported.migrationNetwork(getVm().getVdsGroupCompatibilityVersion())) { return null; } Network migrationNetwork = null; List<Network> allNetworksInCluster = DbFacade.getInstance().getNetworkDao().getAllForCluster(getVm().getVdsGroupId()); for (Network tempNetwork : allNetworksInCluster) { if (tempNetwork.getCluster().isMigration()) { migrationNetwork = tempNetwork; break; } } if (migrationNetwork != null) { if (getMigrationNetworkAddress(getVds().getId(), migrationNetwork.getName()) == null) { return null; } String dstMigrationIp = getMigrationNetworkAddress(getDestinationVds().getId(), migrationNetwork.getName()); if (dstMigrationIp != null) { return dstMigrationIp; } } return null; }

Target:
private String getMigrationNetworkIp() { if (!FeatureSupported.migrationNetwork(getVm().getVdsGroupCompatibilityVersion())) { return null; } Network migrationNetwork = null; List<Network> allNetworksInCluster = DbFacade.getInstance().getNetworkDao().getAllForCluster(getVm().getVdsGroupId()); for (Network tempNetwork : allNetworksInCluster) { if (tempNetwork.getCluster().isMigration()) { migrationNetwork = tempNetwork; break; } } if (migrationNetwork != null) { if (getMigrationNetworkAddress(getVds().getId(), migrationNetwork.getName()) == null) { return null; } return getMigrationNetworkAddress(getDestinationVds().getId(), migrationNetwork.getName()); } return null; }
Source:
public void onCascadeEvent(BeforeWorkspaceRemovedEvent event) throws Exception { Optional<KubernetesRuntimeState> k8sRuntimeStateOpt = k8sRuntimes.find(event.getWorkspace().getId()); if (k8sRuntimeStateOpt.isPresent()) { LOG.error("Workspace is removed but Kubernetes runtime state exists"); KubernetesRuntimeState existingK8sRuntimeState = k8sRuntimeStateOpt.get(); k8sRuntimes.remove(existingK8sRuntimeState.getRuntimeId()); } }

Target:
public void onCascadeEvent(BeforeWorkspaceRemovedEvent event) throws Exception { Optional<KubernetesRuntimeState> k8sRuntimeStateOpt = k8sRuntimes.find(event.getWorkspace().getId()); if (k8sRuntimeStateOpt.isPresent()) { KubernetesRuntimeState existingK8sRuntimeState = k8sRuntimeStateOpt.get(); RuntimeId runtimeId = existingK8sRuntimeState.getRuntimeId(); LOG.error( format( "Workspace is being removed while Kubernetes runtime state '%s:%s:%s' exists. " + "This situation indicates a bug that needs to be reported. Runtime state " + "will be removed from DB, but Kubernetes resources (pods, pvcs, etc.) " + "won't be cleaned up.", runtimeId.getWorkspaceId(), runtimeId.getEnvName(), runtimeId.getOwnerId())); k8sRuntimes.remove(runtimeId); } }
Source:
public static RyaStatement read(Input input){ String subject = input.readString(); String predicate = input.readString(); String objectType = input.readString(); String objectValue = input.readString(); RyaType value; if (objectType.equals("<LINK_0>")){ value = new RyaURI(objectValue); } else { value = new RyaType(new URIImpl(objectType), objectValue); } RyaStatement statement = new RyaStatement(new RyaURI(subject), new RyaURI(predicate), value); int length = 0; boolean hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setContext(new RyaURI(input.readString())); } hasNextValue = input.readBoolean(); if (hasNextValue){ length = input.readInt(); statement.setColumnVisibility(input.readBytes(length)); } hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setQualifer(input.readString()); } hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setTimestamp(input.readLong()); } hasNextValue = input.readBoolean(); if (hasNextValue){ length = input.readInt(); statement.setValue(input.readBytes(length)); } return statement; }

Target:
public static RyaStatement read(Input input){ Preconditions.checkNotNull(input); String subject = input.readString(); String predicate = input.readString(); String objectType = input.readString(); String objectValue = input.readString(); RyaType value; if (objectType.equals(XMLSchema.ANYURI.toString())){ value = new RyaURI(objectValue); } else { value = new RyaType(new URIImpl(objectType), objectValue); } RyaStatement statement = new RyaStatement(new RyaURI(subject), new RyaURI(predicate), value); int length = 0; boolean hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setContext(new RyaURI(input.readString())); } hasNextValue = input.readBoolean(); if (hasNextValue){ length = input.readInt(); statement.setColumnVisibility(input.readBytes(length)); } hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setQualifer(input.readString()); } hasNextValue = input.readBoolean(); if (hasNextValue){ statement.setTimestamp(input.readLong()); } hasNextValue = input.readBoolean(); if (hasNextValue){ length = input.readInt(); statement.setValue(input.readBytes(length)); } return statement; }
Source:
public void shouldSetMonochromeOnPlugin() { RuntimeOptions runtimeOptions = new RuntimeOptions("--monochrome"); Plugins plugins = new Plugins(getSystemClassLoader(), pluginFactory, runtimeOptions); ColorAware plugin = Mockito.mock(ColorAware.class); plugins.addPlugin(plugin); plugins.setSerialEventBusOnEventListenerPlugins(rootEventPublisher); verify(plugin).setMonochrome(true); }

Target:
public void shouldSetMonochromeOnPlugin() { RuntimeOptions runtimeOptions = new RuntimeOptions("--monochrome"); Plugins plugins = new Plugins(getSystemClassLoader(), pluginFactory, runtimeOptions); ColorAware plugin = Mockito.mock(ColorAware.class); plugins.addPlugin(plugin); verify(plugin).setMonochrome(true); }
Source:
private void validate() { int nParams = nodes.size(); for (int i = 0; i < nParams; ++i) { ArgChecker.isTrue(nodes.get(i).getCurrencyPair().equals(currencyPair), "currency pair must be the same"); ArgChecker.isTrue(nodes.get(i).getStrike() instanceof SimpleStrike, "Strike must be SimpleStrike"); ArgChecker.isTrue(nodes.get(i).getQuoteValueType().equals(ValueType.BLACK_VOLATILITY), "quote value type must be BLACK_VOLATILITY"); } }

Target:
private void validate() { int nParams = nodes.size(); for (int i = 0; i < nParams; ++i) { ArgChecker.isTrue(nodes.get(i).getCurrencyPair().equals(currencyPair), "Currency pair must be the same"); ArgChecker.isTrue(nodes.get(i).getStrike() instanceof SimpleStrike, "Strike must be SimpleStrike"); ArgChecker.isTrue(nodes.get(i).getQuoteValueType().equals(ValueType.BLACK_VOLATILITY), "Quote value type must be BLACK_VOLATILITY"); } }
Source:
public static void writeStyle(final InputStream in, final Resource styleFile) throws IOException { BufferedOutputStream out = null; try { out = new BufferedOutputStream(styleFile.out()); IOUtils.copy(in, out); out.flush(); } finally { out.close(); } }

Target:
public static void writeStyle(final InputStream in, final Resource styleFile) throws IOException { try (BufferedOutputStream out = new BufferedOutputStream(styleFile.out())) { IOUtils.copy(in, out); out.flush(); } }
Source:
private void handleNotification(final Observation observation, final LwM2mNode value) { excutorService.submit(new Runnable() { @Override public void run() { String ticket = observatioIdToTicket.get(new KeyId(observation.getId())); try { sendNotification(ticket, value); } catch (Throwable t) { LOG.error("Unable to send Notification.", t); sendError(ticket, String.format("Expected error while sending LWM2M Notification.(%s)", t.getMessage())); } } }); }

Target:
private void handleNotification(final Observation observation, final LwM2mNode value) { executorService.submit(new Runnable() { @Override public void run() { String ticket = observatioIdToTicket.get(new KeyId(observation.getId())); try { sendNotification(ticket, value); } catch (RuntimeException t) { LOG.error("Unable to send Notification.", t); sendError(ticket, String.format("Expected error while sending LWM2M Notification.(%s)", t.getMessage())); } } }); }
Source:
public boolean checkout() throws IOException { toBeDeleted.clear(); if (headCommitTree != null) preScanTwoTrees(); else prescanOneTree(); if (!conflicts.isEmpty()) { if (failOnConflict) { dc.unlock(); throw new CheckoutConflictException(conflicts.toArray(new String[conflicts.size()])); } else cleanUpConflicts(); } builder.finish(); File file=null; String last = ""; for (int i = removed.size() - 1; i >= 0; i--) { String r = removed.get(i); file = new File(repo.getWorkTree(), r); if (!file.delete() && file.exists()) toBeDeleted.add(r); else { if (!isSamePrefix(r, last)) removeEmptyParents(new File(repo.getWorkTree(), last)); last = r; } } if (file != null) removeEmptyParents(file); for (String path : updated.keySet()) { file = new File(repo.getWorkTree(), path); if (!file.getParentFile().mkdirs()) { } DirCacheEntry entry = dc.getEntry(path); if (FileMode.GITLINK.equals(entry.getRawMode())) continue; checkoutEntry(repo, file, entry); } if (!builder.commit()) { dc.unlock(); throw new IndexWriteException(); } return toBeDeleted.size() == 0; }

Target:
public boolean checkout() throws IOException { try { return doCheckout(); } finally { dc.unlock(); } }
Source:
public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); StringWriter out = new StringWriter(); try { XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); } catch (TransformerException|SAXException e) { throw new IOException("Failed to persist configuration.xml", e); } try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8")))){ String oldname = name; Object o = Jenkins.XSTREAM.unmarshal(new Xpp3Driver().createReader(in), this); if (o!=this) { throw new IOException("Expecting "+this.getClass()+" but got "+o.getClass()+" instead"); } name = oldname; } catch (StreamException | ConversionException | Error e) { throw new IOException("Unable to read",e); } save(); }

Target:
public void updateByXml(Source source) throws IOException { checkPermission(CONFIGURE); StringWriter out = new StringWriter(); try { XMLUtils.safeTransform(source, new StreamResult(out)); out.close(); } catch (TransformerException|SAXException e) { throw new IOException("Failed to persist configuration.xml", e); } try (InputStream in = new BufferedInputStream(new ByteArrayInputStream(out.toString().getBytes("UTF-8")))){ String oldname = name; Object o = Jenkins.XSTREAM.unmarshal(new Xpp3Driver().createReader(in), this); if (!o.getClass().equals(getClass())) { throw new IOException("Expecting view type: "+this.getClass()+" but got: "+o.getClass()+" instead." + "\nShould you needed to change to a new view type, you must first delete and then re-create " + "the view with the new view type."); } name = oldname; } catch (StreamException | ConversionException | Error e) { throw new IOException("Unable to read",e); } save(); }
Source:
public void visitNode(Tree tree) { UnaryExpressionTree temp = (UnaryExpressionTree) tree; if (usedForDoublePrefix(temp)) { return; } ExpressionTree expr = ExpressionUtils.skipParentheses(temp.expression()); if (temp.is(expr.kind())) { prefixSet.add(expr); reportIssue(temp.operatorToken(), ((UnaryExpressionTree) expr).operatorToken(), "Remove multiple operator prefixes."); } }

Target:
public void visitNode(Tree tree) { UnaryExpressionTree exprTree = (UnaryExpressionTree) tree; if (alreadyReported(exprTree)) { return; } ExpressionTree expr = ExpressionUtils.skipParentheses(exprTree.expression()); if (exprTree.is(expr.kind())) { UnaryExpressionTree child = (UnaryExpressionTree) expr; if (child.is(Tree.Kind.BITWISE_COMPLEMENT) && !ExpressionUtils.skipParentheses(child.expression()).is(Tree.Kind.BITWISE_COMPLEMENT)) { return; } prefixSet.add(child); reportIssue(exprTree.operatorToken(), child.operatorToken(), "Remove multiple operator prefixes."); } }
Source:
private VirtualMachineScaleSet CreateOrUpdateVMSS(VirtualMachineScaleSetApi vmssAPI) { return vmssAPI.createOrUpdate( vmssname, "eastus", VirtualMachineScaleSetSKU.create( "Standard_A1", "Standard", 10), null, VirtualMachineScaleSetProperties.create( true, true, VirtualMachineScaleSetUpgradePolicy.create("Manual"), VirtualMachineScaleSetVirtualMachineProfile.create( StorageProfile.create( ImageReference.create( null, "Canonical", "UbuntuServer", "16.04-LTS", "latest"), OSDisk.create( "Windows", null, null, null, "FromImage", null, ManagedDiskParameters.create( null, "Standard_LRS"), null), Arrays.asList(DataDisk.create( null, "10", 1, null, null, "FromImage", "None", ManagedDiskParameters.create( null, "Standard_LRS"), null))), VirtualMachineScaleSetOSProfile.create( "jclouds-vmssname", "jclouds", "jClouds1!", VirtualMachineScaleSetOSProfile.LinuxConfiguration.create( "False", null), null, new ArrayList<Secrets>()), getNetworkProfile(), getExtensionProfile() ) )); }

Target:
private VirtualMachineScaleSet CreateOrUpdateVMSS(VirtualMachineScaleSetApi vmssAPI) { return vmssAPI.createOrUpdate( vmssname, "eastus", VirtualMachineScaleSetSKU.create( "Standard_A1", "Standard", 10), null, VirtualMachineScaleSetProperties.create( true, true, VirtualMachineScaleSetUpgradePolicy.create("Manual"), null, VirtualMachineScaleSetVirtualMachineProfile.create( StorageProfile.create( ImageReference.create( null, "Canonical", "UbuntuServer", "16.04-LTS", "latest"), OSDisk.create( "Windows", null, null, null, "FromImage", null, ManagedDiskParameters.create( null, "Standard_LRS"), null), Arrays.asList(DataDisk.create( null, "10", 1, null, null, "FromImage", "None", ManagedDiskParameters.create( null, "Standard_LRS"), null))), VirtualMachineScaleSetOSProfile.create( "jclouds-vmssname", "admin", "password", VirtualMachineScaleSetOSProfile.LinuxConfiguration.create( false, null), null, new ArrayList<Secrets>()), getNetworkProfile(), getExtensionProfile() ) )); }
Source:
public void accumulate(final VariantContext vc) { progress.record(vc.getContig(), vc.getStart()); if (!isVariantExcluded(vc)) { final String singletonSample = getSingletonSample(vc); updateSummaryMetric(summaryMetric, null, vc, singletonSample != null); vc.getSampleNames().stream() .filter(sampleName -> vc.getGenotype(sampleName).isHomRef()) .forEach(sampleName -> sampleMetricsMap.get(sampleName)); vc.getSampleNames().stream() .filter(sampleName -> !vc.getGenotype(sampleName).isHomRef()) .forEach(sampleName -> updateDetailMetric(sampleMetricsMap.get(sampleName), vc.getGenotype(sampleName), vc, sampleName.equals(singletonSample))); } }

Target:
public void accumulate(final VariantContext vc) { progress.record(vc.getContig(), vc.getStart()); if (!isVariantExcluded(vc)) { final String singletonSample = getSingletonSample(vc); updateSummaryMetric(summaryMetric, null, vc, singletonSample != null); vc.getSampleNames().stream() .filter(sampleName -> !vc.getGenotype(sampleName).isHomRef()) .forEach(sampleName -> updateDetailMetric(sampleMetricsMap.get(sampleName), vc.getGenotype(sampleName), vc, sampleName.equals(singletonSample))); } }
Source:
public void process(Class<?> context, Object testInstance) { Field[] fields = context.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) { assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class); field.setAccessible(true); Object instance; try { instance = field.get(testInstance); assertNotInterface(instance, field.getType()); if (MockUtil.isMock(instance)) { Mockito.reset(instance); } else if (instance != null) { field.set(testInstance, Mockito.mock(instance.getClass(), withSettings().spiedInstance(instance) .defaultAnswer(CALLS_REAL_METHODS) .name(field.getName()))); } else { field.set(testInstance, newSpyInstance(testInstance, field)); } } catch (Exception e) { e.printStackTrace(); throw new MockitoException("Unable to initialize @Spy annotated field '" + field.getName() + "'.\n" + e.getMessage(), e); } } } }

Target:
public void process(Class<?> context, Object testInstance) { Field[] fields = context.getDeclaredFields(); for (Field field : fields) { if (field.isAnnotationPresent(Spy.class) && !field.isAnnotationPresent(InjectMocks.class)) { assertNoIncompatibleAnnotations(Spy.class, field, Mock.class, Captor.class); field.setAccessible(true); Object instance; try { instance = field.get(testInstance); assertNotInterface(instance, field.getType()); if (MockUtil.isMock(instance)) { Mockito.reset(instance); } else if (instance != null) { field.set(testInstance, spyInstance(field, instance)); } else { field.set(testInstance, spyNewInstance(testInstance, field)); } } catch (Exception e) { throw new MockitoException("Unable to initialize @Spy annotated field '" + field.getName() + "'.\n" + e.getMessage(), e); } } } }
Source:
public static double[] noDuplicates(double[] argument, String name) { notNull(argument, name); if (argument.length > 0 && DoubleStream.of(argument).distinct().count() != argument.length) { throw new IllegalArgumentException(noDuplicatesArrayMsg(name)); } return argument; }

Target:
public static double[] noDuplicates(double[] argument, String name) { notNull(argument, name); if (argument.length > 1) { Set<Double> seen = new LinkedHashSet<>(); for (double v : argument) { if (!seen.add(v)) { throw new IllegalArgumentException(noDuplicatesArrayMsg(name)); } } } return argument; }
Source:
public Builder setRecordCount(@DnsSection int sec, int count) { if (count < 0) throw new IllegalArgumentException("Bad record count: " + count); mRecordCount[sec] = count; return this; }

Target:
public Builder setRecordCount(@DnsSection int sec, int count) { if (sec > DnsPacket.ARSECTION || sec < DnsPacket.QDSECTION) { throw new IllegalArgumentException("Bad sec: " + sec); } if (count < 0) throw new IllegalArgumentException("Bad record count: " + count); mRecordCount[sec] = count; return this; }
Source:
public IStatus unloadAtResourceSetDispose(Resource resource, IProgressMonitor monitor) { try { if (!isFromPackageRegistry(resource)) { resource.unload(); } } catch (final IllegalStateException e) { return new Status(IStatus.WARNING, SiriusPlugin.ID, MessageFormat.format(Messages.DAnalysisSessionImpl_unloadingErrorMsg, e.getMessage()), e); } return new Status(IStatus.INFO, SiriusPlugin.ID, ""); }

Target:
public IStatus unloadAtResourceSetDispose(Resource resource, IProgressMonitor monitor) { try { if (!isFromPackageRegistry(resource)) { resource.unload(); } } catch (final IllegalStateException e) { return new Status(IStatus.WARNING, SiriusPlugin.ID, MessageFormat.format(Messages.DAnalysisSessionImpl_unloadingErrorMsg, e.getMessage()), e); } return new Status(IStatus.OK, SiriusPlugin.ID, ""); }
Source:
public void teardown() throws Exception { dbHelper.onTearDown(); configHelper.onTearDown(); notifier.enableUpdates(); }

Target:
public void teardown() throws Exception { notifier.enableUpdates(); dbHelper.onTearDown(); configHelper.onTearDown(); }
Source:
public void testIndexSeekAndScan() throws Exception { updateAndCommit( asList( IndexEntryUpdate.add( 1L, descriptor, "a", "a" ), IndexEntryUpdate.add( 2L, descriptor, "a", "a" ), IndexEntryUpdate.add( 3L, descriptor, "b", "b" ) ) ); assertThat( getAllNodesWithProperties( "a", "a" ), equalTo( asList( 1L, 2L ) ) ); assertThat( getAllNodes(), equalTo( asList( 1L, 2L, 3L ) ) ); }

Target:
public void testIndexSeekAndScan() throws Exception { updateAndCommit( asList( IndexEntryUpdate.add( 1L, descriptor, "a", "a" ), IndexEntryUpdate.add( 2L, descriptor, "a", "a" ), IndexEntryUpdate.add( 3L, descriptor, "b", "b" ), IndexEntryUpdate.add( 4L, descriptor, "a", "b" ) ) ); assertThat( query( exact( 0, "a" ), exact( 1, "a" ) ), equalTo( asList( 1L, 2L ) ) ); assertThat( query( exact( 0, "b" ), exact( 1, "b" ) ), equalTo( asList( 3L ) ) ); assertThat( query( exact( 0, "a" ), exact( 1, "b" ) ), equalTo( asList( 4L ) ) ); assertThat( query( exists( 1 ) ), equalTo( asList( 1L, 2L, 3L, 4L ) ) ); }
Source:
public RecordWriter getRecordWriter(final HdfsSinkConnectorConfig conf, final String filename) { try { return new RecordWriter() { final Path path = new Path(filename); final OutputStream out = path.getFileSystem(conf.getHadoopConfiguration()).create(path); final OutputStreamWriter writer = new OutputStreamWriter(out); @Override public void write(SinkRecord record) { log.trace("Sink record: {}", record.toString()); try { String value = (String) record.value(); writer.write(value); writer.write(LINE_SEPARATOR); } catch (IOException e) { throw new ConnectException(e); } } @Override public void commit() @Override public void close() { try { writer.close(); } catch (IOException e) { throw new ConnectException(e); } } }; } catch (IOException e) { throw new ConnectException(e); } }

Target:
public RecordWriter getRecordWriter(final HdfsSinkConnectorConfig conf, final String filename) { try { return new RecordWriter() { final Path path = new Path(filename); final OutputStream out = path.getFileSystem(conf.getHadoopConfiguration()).create(path); final OutputStreamWriter streamWriter = new OutputStreamWriter( out, Charset.defaultCharset() ); final BufferedWriter writer = new BufferedWriter(streamWriter, WRITER_BUFFER_SIZE); @Override public void write(SinkRecord record) { log.trace("Sink record: {}", record.toString()); try { String value = (String) record.value(); writer.write(value); writer.newLine(); } catch (IOException e) { throw new ConnectException(e); } } @Override public void commit() @Override public void close() { try { writer.close(); } catch (IOException e) { throw new ConnectException(e); } } }; } catch (IOException e) { throw new ConnectException(e); } }
Source:
public boolean isStaticQnNumberVisible(int qnNumber) { WebElement discardChangesButton = browser.driver.findElement( By.id(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER_STATIC + "-" + qnNumber)); return discardChangesButton.isDisplayed(); }

Target:
public boolean isStaticQnNumberVisible(int qnNumber) { try { WebElement selectQuestionNumberStatic = browser.driver.findElement(By.id(Const.ParamsNames.FEEDBACK_QUESTION_NUMBER_STATIC + "-" + qnNumber)); return selectQuestionNumberStatic.isDisplayed(); } catch (NoSuchElementException nsee) { return false; } }
Source:
private void flush() { synchronized (lock) { tableToBulkMutation.values().stream().forEach(mutation -> { try { mutation.flush(); } catch (final InterruptedException e) { throw new RuntimeException(e); } }); } }

Target:
private void flush() { synchronized (flushLock) { tableToBulkMutation.values().stream().forEach(mutation -> { try { mutation.flush(); } catch (final InterruptedException e) { throw new RuntimeException(e); } }); } }
Source:
private void registerServerTransactionTable(ComponentRegistry componentRegistry, String cacheName) { if (GLOBAL_TX_TABLE_CACHE_NAME.equals(cacheName) || !componentRegistry.getComponent(Configuration.class).transaction().transactionMode().isTransactional()) { return; } EmbeddedCacheManager cacheManager = componentRegistry.getGlobalComponentRegistry() .getComponent(EmbeddedCacheManager.class); createGlobalTxTable(cacheManager); BasicComponentRegistry basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.replaceComponent(PerCacheTxTable.class.getName(), new PerCacheTxTable(cacheManager.getAddress()), true); basicComponentRegistry.replaceComponent(TransactionOriginatorChecker.class.getName(), new ServerTransactionOriginatorChecker(), true); basicComponentRegistry.rewire(); componentRegistry.rewire(); }

Target:
private void registerServerTransactionTable(ComponentRegistry componentRegistry, String cacheName) { if (GLOBAL_TX_TABLE_CACHE_NAME.equals(cacheName) || !componentRegistry.getComponent(Configuration.class).transaction().transactionMode().isTransactional()) { return; } EmbeddedCacheManager cacheManager = componentRegistry.getGlobalComponentRegistry() .getComponent(EmbeddedCacheManager.class); createGlobalTxTable(cacheManager); BasicComponentRegistry basicComponentRegistry = componentRegistry.getComponent(BasicComponentRegistry.class); basicComponentRegistry.replaceComponent(PerCacheTxTable.class.getName(), new PerCacheTxTable(cacheManager.getAddress()), true); basicComponentRegistry.replaceComponent(TransactionOriginatorChecker.class.getName(), new ServerTransactionOriginatorChecker(), true); componentRegistry.rewire(); }
Source:
public boolean equals(byte[] obj, Object otherObj) { if (obj == otherObj) return true; if (obj == null || byte[].class != obj.getClass()) return false; if (otherObj == null || byte[].class != otherObj.getClass()) return false; byte[] byteArray = obj; byte[] otherByteArray = (byte[]) otherObj; return Arrays.equals(byteArray, otherByteArray); }

Target:
public boolean equals(byte[] obj, Object otherObj) { if (obj == otherObj) return true; if (obj == null) return false; if (otherObj == null || byte[].class != otherObj.getClass()) return false; byte[] otherByteArray = (byte[]) otherObj; return Arrays.equals(obj, otherByteArray); }
Source:
public MaintenanceWorkflow() { super(MAINTENANCE_WORKFLOW_TYPE); setDescription("Do nFlow maintenance periodically."); }

Target:
public MaintenanceWorkflow() { super(MAINTENANCE_WORKFLOW_TYPE); setDescription("Clean up workflow instances periodically."); }
Source:
public IgniteConfiguration() { compressorsSelector = new HashMap<>(); compressorsSelector.put(CompressionType.GZIP, new GZipCompressor()); compressorsSelector.put(CompressionType.DEFLATE, new DeflaterCompressor()); fullCompressionType = CompressionType.GZIP; }

Target:
public IgniteConfiguration() { }
Source:
public Change(String entityId, long revision, Date timestamp, long rcid) { if (entityId.startsWith("Property:")) { this.entityId = entityId.substring("Property:".length()); } else if (entityId.startsWith("Item:")) { this.entityId = entityId.substring("Item:".length()); } else { this.entityId = entityId; } this.revision = revision; this.timestamp = timestamp != null ? new Date(timestamp.getTime()) : null; this.rcid = rcid; }

Target:
public Change(String entityId, long revision, Date timestamp, long rcid) { if (entityId.startsWith("Property:")) { this.entityId = entityId.substring("Property:".length()); } else if (entityId.startsWith("Item:")) { this.entityId = entityId.substring("Item:".length()); } else { this.entityId = entityId; } this.revision = revision; this.timestamp = timestamp; this.rcid = rcid; }
Source:
private Jwt validateJwt(Jwt jwt) { OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt); if ( result.hasErrors() ) { final Collection<OAuth2Error> errors = result.getErrors(); final Optional<String> validationErrorString = errors.stream() .map(OAuth2Error::getDescription) .filter(Objects::nonNull) .findFirst(); throw new JwtValidationException(validationErrorString.orElse("Unable to validate Jwt"), errors); } return jwt; }

Target:
private Jwt validateJwt(Jwt jwt) { OAuth2TokenValidatorResult result = this.jwtValidator.validate(jwt); if ( result.hasErrors() ) { final Collection<OAuth2Error> errors = result.getErrors(); String validationErrorString = "Unable to validate Jwt"; for (OAuth2Error oAuth2Error: errors){ if (!StringUtils.isEmpty(oAuth2Error.getDescription())) { validationErrorString = oAuth2Error.getDescription(); break; } } throw new JwtValidationException(validationErrorString, errors); } return jwt; }
Source:
private static Extent extentFromSource(CommandSource origin) { if (origin instanceof ICommandSender) { return (Extent) ((ICommandSender) origin).getEntityWorld(); } return null; }

Target:
private static Extent extentFromSource(CommandSource origin) { if (origin instanceof LocatedSource) { return ((LocatedSource) origin).getWorld(); } return null; }
Source:
protected Map<String, Pair<String, String>> getSharedLocks() { Map<String, Pair<String, String>> locks = new HashMap<>(); if (isTemplateVersion()) { locks.put(getParameters().getBaseTemplateId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } locks.put(getParameters().getVm().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_VM_IS_BEING_CLONED)); return locks; }

Target:
protected Map<String, Pair<String, String>> getSharedLocks() { Map<String, Pair<String, String>> locks = new HashMap<>(); if (isTemplateVersion()) { locks.put(getParameters().getBaseTemplateId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.TEMPLATE, EngineMessage.ACTION_TYPE_FAILED_OBJECT_LOCKED)); } locks.put(getParameters().getVm().getId().toString(), LockMessagesMatchUtil.makeLockingPair(LockingGroup.VM, EngineMessage.ACTION_TYPE_FAILED_TEMPLATE_IS_BEING_CREATED)); return locks; }
Source:
public static CassandraKeyValueService create( MetricsManager metricsManager, CassandraKeyValueServiceConfig config, CassandraMutationTimestampProvider mutationTimestampProvider, CassandraClientPool clientPool) { return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, Optional.empty(), mutationTimestampProvider, LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }

Target:
public static CassandraKeyValueService create( MetricsManager metricsManager, CassandraKeyValueServiceConfig config, CassandraMutationTimestampProvider mutationTimestampProvider, CassandraClientPool clientPool) { return createOrShutdownClientPool(metricsManager, config, CassandraKeyValueServiceRuntimeConfig::getDefault, clientPool, mutationTimestampProvider, LoggerFactory.getLogger(CassandraKeyValueService.class), AtlasDbConstants.DEFAULT_INITIALIZE_ASYNC); }
Source:
public void parseFromBufferedReaderTest() throws IOException { YoutubeScraper ytubeScrape = new YoutubeScraper(); String url = "<LINK_0>"; String postType = "video"; String postScraper = "youtube"; try { BufferedReader br = new BufferedReader(new InputStreamReader((new URL(url)).openStream(), StandardCharsets.UTF_8)); Post video = ytubeScrape.parseVideo(br, "url", "<LINK_0>"); DAO.log(video.toString()); assertThat(video.get("html_title").toString(), is("[\"Iggy Azalea - Team (Explicit) - YouTube\"]")); assertEquals(postType, video.get("post_type")); assertEquals(postScraper, video.get("post_scraper")); } catch (IOException e) { DAO.log("YoutubeScraperTest.parseFromBufferedReaderTest()() failed to connect to network. url:" + url); } }

Target:
public void parseFromBufferedReaderTest() throws IOException { YoutubeScraper ytubeScrape = new YoutubeScraper(); String url = "<LINK_0>"; String postType = "video"; String postScraper = "youtube"; try { BufferedReader br = new BufferedReader(new InputStreamReader((new URL(url)).openStream(), StandardCharsets.UTF_8)); Post video = ytubeScrape.parseVideo(br, "url", "<LINK_0>"); DAO.log(video.toString()); assertThat(video.get("html_title").toString(), is("[\"Iggy Azalea - Team (Explicit) - YouTube\"]")); assertThat(video.get("post_type"), is(postType)); assertThat(video.get("post_scraper"), is(postScraper)); } catch (IOException e) { DAO.log("YoutubeScraperTest.parseFromBufferedReaderTest()() failed to connect to network. url:" + url); } }
Source:
public void testStringInputRowParserSerde() throws Exception { final StringInputRowParser parser = new StringInputRowParser( new JSONParseSpec( new TimestampSpec("timestamp", "iso", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("foo", "bar")), null, null), null, null, false ), null ); final ByteBufferInputRowParser parser2 = jsonMapper.readValue( jsonMapper.writeValueAsBytes(parser), ByteBufferInputRowParser.class ); final InputRow parsed = parser2.parseBatch( ByteBuffer.wrap(StringUtils.toUtf8("{\"foo\":\"x\",\"bar\":\"y\",\"qux\":\"z\",\"timestamp\":\"2000\"}")) ).get(0); Assert.assertEquals(ImmutableList.of("foo", "bar"), parsed.getDimensions()); Assert.assertEquals(ImmutableList.of("x"), parsed.getDimension("foo")); Assert.assertEquals(ImmutableList.of("y"), parsed.getDimension("bar")); Assert.assertEquals(DateTimes.of("2000").getMillis(), parsed.getTimestampFromEpoch()); }

Target:
public void testStringInputRowParserSerde() throws Exception { final StringInputRowParser parser = new StringInputRowParser( new JSONParseSpec( new TimestampSpec("timestamp", "iso", null), new DimensionsSpec(DimensionsSpec.getDefaultSchemas(ImmutableList.of("foo", "bar")), null, null), null, null, null ), null ); final ByteBufferInputRowParser parser2 = jsonMapper.readValue( jsonMapper.writeValueAsBytes(parser), ByteBufferInputRowParser.class ); final InputRow parsed = parser2.parseBatch( ByteBuffer.wrap(StringUtils.toUtf8("{\"foo\":\"x\",\"bar\":\"y\",\"qux\":\"z\",\"timestamp\":\"2000\"}")) ).get(0); Assert.assertEquals(ImmutableList.of("foo", "bar"), parsed.getDimensions()); Assert.assertEquals(ImmutableList.of("x"), parsed.getDimension("foo")); Assert.assertEquals(ImmutableList.of("y"), parsed.getDimension("bar")); Assert.assertEquals(DateTimes.of("2000").getMillis(), parsed.getTimestampFromEpoch()); }